如何阻止 Tkinter Frame 缩小以适应其内容?

问题描述:

这是给我带来麻烦的代码.

This is the code that's giving me trouble.

f = Frame(root, width=1000, bg="blue")
f.pack(fill=X, expand=True)

l = Label(f, text="hi", width=10, bg="red", fg="white")
l.pack()

如果我用 Label 注释掉这些行,框架就会以正确的宽度显示.但是,添加 Label 似乎会将 Frame 缩小到 Label 的大小.有没有办法防止这种情况发生?

If I comment out the lines with the Label, the Frame displays with the right width. However, adding the Label seems to shrink the Frame down to the Label's size. Is there a way to prevent that from happening?

默认情况下,packgrid 都会缩小或增大小部件以适应其内容,即99.9% 的时候你想要什么.描述此功能的术语是几何传播.使用 pack (pack_propagate) 和 grid (grid_propagate) 时,有一个命令可以打开或关闭几何传播.

By default, both pack and grid shrink or grow a widget to fit its contents, which is what you want 99.9% of the time. The term that describes this feature is geometry propagation. There is a command to turn geometry propagation on or off when using pack (pack_propagate) and grid (grid_propagate).

由于您使用的是 pack,语法将是:

Since you are using pack the syntax would be:

f.pack_propagate(0)

或者可能是 root.pack_propagate(0),具体取决于您实际想要影响的小部件.但是,因为您没有给出框架高度,它的默认高度是一个像素,所以您仍然可能看不到内部小部件.为了获得您想要的全部效果,您需要为包含框架指定宽度和高度.

or maybe root.pack_propagate(0), depending on which widgets you actually want to affect. However, because you haven't given the frame height, its default height is one pixel so you still may not see the interior widgets. To get the full effect of what you want, you need to give the containing frame both a width and a height.

话虽如此,大多数情况下您应该让 Tkinter 计算大小.当您关闭几何传播时,您的 GUI 将无法很好地响应分辨率的变化、字体的变化等.Tkinter 的几何管理器(packplacegrid) 非常强大.您应该学会通过使用适合工作的工具来利用这种力量.

That being said, the vast majority of the time you should let Tkinter compute the size. When you turn geometry propagation off your GUI won't respond well to changes in resolution, changes in fonts, etc. Tkinter's geometry managers (pack, place and grid) are remarkably powerful. You should learn to take advantage of that power by using the right tool for the job.