简体   繁体   中英

Stretching frames using grid layout in Python Tkinter

I'm trying to get stretching to work using Python 2.6.7 with Tkinter. I'd expect the below code to stretch the first button to the width of the second, but both buttons are only as wide as they need to be to fit their text.

#!/usr/bin/python
from Tkinter import *

win = Frame()
win.grid(sticky=N+S+E+W)

inner_a = Frame(win)
inner_a.grid(row=0, column=0, sticky=N+E+W)
inner_b = Frame(win)
inner_b.grid(row=1, column=0, sticky=S+E+W)

Button(inner_a, text='1').grid(row=0, column=0, sticky=E+W)
Button(inner_b, text='Some long text').grid(row=0, column=0, sticky=E+W)

win.mainloop()

By my understanding, the single column in win will expand to the width of the largest thing it contains, ie the width of inner_b , and then the width of inner_a , and thence of the first button, will be that of the second button.

Actually, what happens is the below; the first button is only wide enough to contain "1", not as wide as the second button.

屏幕截图:两个按钮叠在一起,第一个有单个字符“1”,第二个有“一些长文本”。底部按钮比顶部宽得多。

What do I need to do to get the first button to expand the size of the second?

If you want widgets to line up in a grid, the first thing to do is make sure they have the same parent. This isn't strictly necessary if all the widgets are the same size or you are only using one column.

Another thing you need to do is give your column a weight. What is happening in your code is that the widget is expanding to fill the column, but the column isn't expanding to fill the master. If you give it a weight of 1 it will. You ned to do something like inner_a.columnconfigure(1, weight=1) , and then do likewise for inner_b .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM