Question

I'm missing something about how sizes propagate in Tk. Try this:

from Tkinter import *

root = Tk()

frame1 = Frame(root, border=4, relief=RIDGE)
frame1.grid(sticky=E+W)
frame2 = Frame(root, border=4, relief=RIDGE)
frame2.grid(sticky=E+W)

label1 = Label(frame1, text='short', background='white')
label1.grid(sticky=E+W)
label2 = Label(frame2, text='quite a bit longer', background='white')
label2.grid(sticky=E+W)

root.mainloop()

label1 is inside frame1, and label2 is inside frame2. label1 comes out narrower than label2, as seen by the white background. But frame1 and frame2 are the same width, as seen by their borders. I thought the stickiness would expand label1 to be the same width as its parent.

If I put label1 and label2 inside the same frame, then label1 comes out as wide as label2:

frame1 = Frame(root, border=4, relief=RIDGE)
frame1.grid(sticky=E+W)

label1 = Label(frame1, text='short', background='white')
label1.grid(sticky=E+W)
label2 = Label(frame1, text='quite a bit longer', background='white')
label2.grid(sticky=E+W)

What am I missing? In real life, I have some stacked nested frames that are not expanding as I would like.

Thanks, Dan

Was it helpful?

Solution

Rows and columns have "weight" which describes how they grow or shrink to fill extra space in the master. By default a row or column has a weight of zero, which means you've told the label to fill the column but you haven't told the column to fill the master frame.

To fix this, give the column a weight. Any positive integer will do in this specific case:

frame1.columnconfigure(0, weight=1)
frame2.columnconfigure(0, weight=1)

For more info on grid, with examples in ruby, tcl, perl and python, see the grid page on tkdocs.com

OTHER TIPS

This solution with columns and frames works, but to get labels to have the same width in a grid, you do not need the enclosing frames. See below example

from tkinter import *

root = Tk()

label1 = Label(root, text='short', bg='light green', relief=RIDGE)
label1.grid(sticky=E+W)
label2 = Label(root, text='quite a bit longer', bg='light green', relief=RIDGE)
label2.grid(sticky=E+W)

root.mainloop()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top