简体   繁体   English

在Python Tkinter中使用网格布局拉伸框架

[英]Stretching frames using grid layout in Python Tkinter

I'm trying to get stretching to work using Python 2.6.7 with Tkinter. 我正在尝试使用Python 2.6.7与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. 根据我的理解, win的单列将扩展到它包含的最大内容的宽度,即inner_b的宽度,然后是inner_a的宽度,以及第一个按钮的宽度,将是第二个按钮的宽度。

Actually, what happens is the below; 实际上,下面会发生什么; the first button is only wide enough to contain "1", not as wide as the second button. 第一个按钮的宽度足以包含“1”,而不是第二个按钮的宽度。

屏幕截图:两个按钮叠在一起,第一个有单个字符“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. 如果你给它一个1的重量。 You ned to do something like inner_a.columnconfigure(1, weight=1) , and then do likewise for inner_b . 您需要执行类似inner_a.columnconfigure(1, weight=1) ,然后对inner_b执行inner_b

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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