Resizing of widgets if we maximize the window

Viewed 139

I want to expand the widget if the window is maximized. Please find the below sample code, if we run this we will get some treeview but if we maximize the window then the treeview will move to left corner, is it possible to get that view expand and fit perfectly after maximized. Thank you

import os
import tkinter as tk
import tkinter.ttk as ttk
import datetime
import re
import threading


class Window:
    i=0
    def __init__(self,master):
        self.master=master
        self.master.geometry('700x350+350+100')
        self.label = tk.Label(self.master, text='Sample', font=("Arial", 20)).grid(row=0,columnspan=3)
        cols = ('A','B','C')
        self.treeview = ttk.Treeview(self.master, columns=cols)
        v_scrollbar = ttk.Scrollbar(self.master, orient='vertical', command=self.treeview.yview)
        self.treeview.config( yscrollcommand=v_scrollbar.set)
        for col in cols:
            self.treeview.heading(col, text=col)
            self.treeview.column(col,minwidth=0,width=170)
        
        self.treeview.grid(row=1, column=0)
        v_scrollbar.grid(row=1, column=1, sticky='nes')
        
        

#--- main---

def main():
    root = tk.Tk()
    
    Window(root)
    root.mainloop()
    
if __name__ == '__main__':
    main()
1 Answers

First add:

self.master.rowconfigure(1, weight=1)
self.master.columnconfigure(0, weight=1)

to tell the layout manager to expand the cell where the treeview is put to fill the available space.

Then add sticky='nsew' to self.treeview.grid(...):

self.treeview.grid(row=1, column=0, sticky='nsew')

Below is the modified __init__():

def __init__(self,master):
    self.master=master
    self.master.geometry('700x350+350+100')
    tk.Label(self.master, text='Sample', font=("Arial", 20)).grid(row=0,columnspan=3)
    cols = ('A','B','C')
    self.treeview = ttk.Treeview(self.master, columns=cols)
    v_scrollbar = ttk.Scrollbar(self.master, orient='vertical', command=self.treeview.yview)
    self.treeview.config( yscrollcommand=v_scrollbar.set)
    for col in cols:
        self.treeview.heading(col, text=col)
        self.treeview.column(col,minwidth=0,width=170)
    
    self.treeview.grid(row=1, column=0, sticky='nsew') # added sticky='nsew'
    v_scrollbar.grid(row=1, column=1, sticky='ns')

    # tell layout manager to expand the cell where the treeview is
    self.master.rowconfigure(1, weight=1)
    self.master.columnconfigure(0, weight=1)
Related