1

I have a window containing widgets with a grid layout, created by this code:

from tkinter import *

window = Tk()

label = Label(text="that label")
label.grid(row=0, column=0, sticky='EW')

entry = Entry()
entry.grid(row=1, column=0, sticky='EW')

window.mainloop()

I would expect the label and entry widget to resize with the window, but if I enlarge the window, it looks like this:

window using grid manager

If I use pack instead of grid (with the fill option) like so:

from tkinter import *

window = Tk()

label = Label(text="that label")
label.pack(fill=X)

entry = Entry()
entry.pack(fill=X)

window.mainloop()

Then the enlarged window looks like this (what I would want it to look like): window using pack manager

Why don't the widgets resize with the window when using grid and how do I make them do it?

LukasFun
  • 171
  • 1
  • 4
  • 17
  • See https://stackoverflow.com/questions/45847313/what-does-weight-do-in-tkinter. Your question isn't an exact duplicate of that, but the answer to that question will likely answer this question. – Bryan Oakley Jan 12 '22 at 17:33

1 Answers1

1

As to why the grid geometry manager doesn't do this automatically - I don't really know. Maybe someone can elaborate on this?

But the solution is very simple: Using grid_columnconfigure (or grid_rowconfigure respectively):

This is a function associated with a frame/window object that takes as parameters the column (or row) it modifies (can also be a list of indices or the keyword all for all columns/rows) and parameters to configure (see the documentation for a detailed description).

To get the widgets to resize with their master object, the parameter weight has to be set to a nonzero value. Your example would look like this:

from tkinter import *

window = Tk()

label = Label(text="that label")
label.grid(row=0, column=0, sticky='EW')

entry = Entry()
entry.grid(row=1, column=0, sticky='EW')

window.grid_columnconfigure(0, weight=1)

window.mainloop()

If you run the code the label and entry widget will change size accordingly: window with columnconfigure

Note that if you use different values for weight for different columns/rows, their relation will determine how the extra space gets split up between them.

LukasFun
  • 171
  • 1
  • 4
  • 17
  • _"As to why the grid geometry manager doesn't do this automatically - I don't really know. Maybe someone can elaborate on this?"_ - probably because any guess that `grid` about which rows or columns to expand will be wrong as often as it is right. It's better just to let the programmer decide. – Bryan Oakley Jan 12 '22 at 17:31