Python Tkinter: responsive grid
Solution 1
As a rule of thumb, whenever you use grid
you should always give at least one row and one column a non-zero weight so that tkinter knows where to allocate extra space. A weight of 0 (zero) is assigned by default.
The two most common cases are where you have a "hero" widget (eg: a text widget, canvas widget, etc) that should grow and shrink as necessary, or you want everything to resize equally. For the case where one widget gets all the extra space, give a weight just to the row and column where that widget is placed. If you want everything to resize equally, give each row and each column a weight.
Assuming that the parent of your widgets content
, userButt
, etc are root
, you might do it like this:
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
In the above example, all extra space would go to row zero and column 0.
Solution 2
Suppose you have a window that is managed by grid system and you want to make it responsive knowing the total number of rows and column you used. Let's say the total number of rows =6 and the total number of columns =10 making the window responsive under grid management system can be done as follows.
n_rows =6
n_columns =10
for i in range(n_rows):
root.grid_rowconfigure(i, weight =1)
for i in range(n_columns):
root.grid_columnconfigure(i, weight =1)
Solution 3
You need to use grid_rowconfigure(<row number>,weight=<row weight>)
and grid_columnconfigure
to stretch rows/columns when container is being stretched. Also use grid(sticky=NSEW)
attribute to stretch items inside a grid
from tkinter import *
root = Tk()
for i in range(10):
root.grid_rowconfigure(i, weight=1)
for j in range(10):
root.grid_columnconfigure(j, weight=1)
Button(root, text=f'Button {i}-{j}').grid(row=i, column=j, sticky=NSEW)
root.mainloop()
Kevin Jordil
Updated on June 04, 2022Comments
-
Kevin Jordil almost 2 years
I have a frame with multiple child elements, that are placed in it using the
grid()
geometry manager.How can I modify the code below to make the frame responsive?
content.grid(column=0, row=0, sticky='nwse') userButt.grid(column=2, row=1, sticky='nwse') favoButt.grid(column=3, row=1, sticky='nwse') locaButt.grid(column=4, row=1, sticky='nwse') histScal.grid(column=5, row=1, sticky='nwse')
-
LW001 over 6 yearsPlease make your question clearer by editing it.
-
CommonSense over 6 yearsDefine "responsive". If behind your wording it's "responsive to window resizing" then read this (especially "Handling resize" part).
-
-
Kevin Jordil almost 4 yearsThanks for your answer, it's been a long time since I finished this project, maybe it will be useful for someone else.
-
crispengari almost 4 yearsYou are welcome man i just come across the same problem and i figure out the solution so i just shared this solution maybe someone can find it helpful
-
GramThanos about 3 yearsPlease also provide information about the code so that the OP can understand it.