Tk Grid Form Resize

Most of the places that explain how Tk’s grid works will tell you the following:

(The examples are made with Python but should work with any language that supports Tk.)

Use “columnconfigure” and “rowconfigure” with a “weight” of at least 1 on each column and row inside the frame. So for a 2×2 grid:

myFrame.columnconfigure(0, weight=1)
myFrame.columnconfigure(1, weight=1)
myFrame.rowconfigure(0, weight=1)
myFrame.rowconfigure(1, weight=1)

Use the “sticky” option for every widget that needs to stick to at least one side of its container. So let’s say we put a button into each cell created above and make them stick to all four sides of their cell:

myButton1.grid(column=0, row=0, sticky=(N,S,E,W))
myButton2.grid(column=1, row=0, sticky=(N,S,E,W))
myButton3.grid(column=0, row=1, sticky=(N,S,E,W))
myButton4.grid(column=1, row=1, sticky=(N,S,E,W))

But even after doing this, which can take quite some time on large interfaces, it still doesn’t seem to work. The missing element, which no one seems to tell, is that the “root” container also has to be set to a weight greater than 0 with “columnconfigure” and “rowconfigure”. In this case we just need to do it for the cell (0,0) because the frame takes care of all other divisions of the window. So as it is suggested in various places, you probably have something like this in your main file:

root = Tk()
root.title("My application")

Which means that “root”, too, has to be configured by adding:

root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)

And now, your widgets should stick to what you set them to.
Here’s the full code of the example:

#!/usr/bin/python

from tkinter import *
from tkinter import ttk

root = Tk()
root.title("My application")
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)

frame = ttk.Frame(root)
frame.columnconfigure(0, weight=1)
frame.columnconfigure(1, weight=1)
frame.rowconfigure(0, weight=1)
frame.rowconfigure(1, weight=1)
frame.grid(column=0, row=0, sticky=(N,S,E,W))

button1 = ttk.Button(frame, text="Button1", command=lambda: print("Button1"))
button2 = ttk.Button(frame, text="Button2", command=lambda: print("Button2"))
button3 = ttk.Button(frame, text="Button3", command=lambda: print("Button3"))
button4 = ttk.Button(frame, text="Button4", command=lambda: print("Button4"))
button1.grid(column=0, row=0, sticky=(N,S,E,W))
button2.grid(column=1, row=0, sticky=(N,S,E,W))
button3.grid(column=0, row=1, sticky=(N,S,E,W))
button4.grid(column=1, row=1, sticky=(N,S,E,W))

root.mainloop()

Leave a Reply