Tkinter grid geometry manager size propagation (with sticky)

ⅰ亾dé卋堺 提交于 2019-12-08 16:27:38

问题


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


回答1:


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




回答2:


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()


来源:https://stackoverflow.com/questions/1441134/tkinter-grid-geometry-manager-size-propagation-with-sticky

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!