2
votes

I am building a fairly complicated GUI in TKinter so naturally have been using the .grid function.

I have grouped some of my widgets into Frames to make them easier to handle, but for some reason when I use .grid with widgets in a frame, the sticky attribute does not seem to work - my widgets don't fill the whole frame.

Example:

f3 = tk.Frame(self, borderwidth=1, relief="ridge")
f3.grid(row=0, column=0, sticky="NS")
tk.Label(f3, text="Site List").grid(in_=f3, row=0, column=0)
self.sitelist = tk.Listbox(f3)
self.sitelist.grid(in_=f3, row=1, column=0, sticky="NS")

In the above code, the frame f3 fills the space in the 0,0 cell of my root widget, but the Listbox does not fill all the space in the Frame, even though I have asked it to be sticky "NS".

If put the Listbox in the root widget at 0,0 then it stretches and fills all the space fine. It just does not behave well if it is in the Frame.

Can anyone explain how to get around this?

I thought that using frames would simplify my layout, but it is not!!!

Cheers. Chris

2

2 Answers

5
votes

You need to give one or more columns and rows "weight". Typically you'll have exactly one row and one column with a weight of 1 (the default is zero). Any row or column with a weight will expand and contract when the containing widget or window is resized.

If more than one row or more than one column has a weight, the weight describes the proportion in which they expand. For example, if one column has a weight of 2 and another a weight of 1, the one with two will expand twice as much as the one with 1.

You can assign weight using the grid_rowconfigure and grid_columnconfigure options to the containing widget:

f3.grid_rowconfigure(0, weight=1)
f3.grid_columnconfigure(0, weight=1)

For a nice brief description of weights, see the section titled Handling Resize on the grid tutorial on the tkdocs.com website.

1
votes

First of all you shouldn't grid the lable at the same time when you instantiate it. Then, you have to use Grid.rowconfigure to add 'weight' to the row and Grid.columnconfigure to add it to the column. The weight controls expansion and has to be non-zero to allow grid to expand widgets. If you add the following lines to your code it should work:

Grid.columnconfigure(f3, 0, weight=1)
Grid.rowconfigure(f3, 0, weight=1)
Grid.rowconfigure(f3, 1, weight=1)

Hope it helps