在Tkinter中向框架添加标签会忽略框架的属性 [英] Adding label to frame in Tkinter ignores the attributes of frame

查看:91
本文介绍了在Tkinter中向框架添加标签会忽略框架的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个固定大小的框架,现在我想在上面添加一些标签和其他小部件.但是我观察到,一旦我在该框架上添加新的小部件,其属性即会失效,即尺寸和默认的背景色设置均会失效.

I have created a frame of fixed size and now i want to add some labels and other widgets on it. But i observed as soon as i add new widget on this frame its attributes are not honored i.e. size and default back ground color set is not honored.

from Tkinter import *
tk = Tk()
page1 = Frame(tk, bg="blue", width=100, height=200)
l1 = Label(page1, text='This is label 1')
page1.pack()
l1.pack()
tk.mainloop()

因此,在上面的示例中,如果我注释掉第4行和6,然后我可以看到一个固定大小的框架,带有蓝色背景色.我的要求是我要在此框架上以这种颜色添加其他一些小部件.

So in the above example if i comment out line 4 & 6, then i can see a frame of fixed size with blue background color. My requirement is I want to add some other widgets on this frame with this color.

推荐答案

关于宽度和高度不被接受,但与背景颜色无关,您是正确的.背景颜色不受影响,但是您看不到背景,因为背景正好适合标签周围.如果在包装时在标签上添加填充物,则会看到背景.

You are correct about the width and height not being honored, but not about the background color. The background color is unaffected, but you can't see the background because the background fits precisely around the label. If you add padding to the label when you pack it you'll see the background.

宽度和高度...这是Tkinter的一大特色.默认情况下,容器窗口小部件会扩展或折叠以使其大小足以容纳其内容.因此,当您调用pack时,它将导致帧缩小.此功能称为几何传播.

As for the width and height... this is one of the great features of Tkinter. By default, a container widget expands or collapses to be just big enough to hold its contents. Thus, when you call pack, it causes the frame to shrink. This feature is called geometry propagation.

对于大多数应用程序来说,这是您想要的行为.在极少数情况下,当您想显式设置容器的大小时,可以关闭此功能.要关闭它,请在容器上调用pack_propagategrid_propagate(取决于您在该容器上使用网格还是打包),并将其值设置为False.

For the vast majority of applications, this is the behavior you want. For those rare times when you want to explicitly set the size of a container you can turn this feature off. To turn it off, call either pack_propagate or grid_propagate on the container (depending on whether you're using grid or pack on that container), giving it a value of False.

以您的代码为例,您将执行以下操作:

Using your code as an example, you would do:

page1.pack_propagate(False)

我的建议是不要这样做,而应该学习如何处理几何体传播.当用户调整窗口大小时,它将使您的GUI表现更好,并且您将不会花费时间来尝试为窗口计算正确的大小.让Tkinter为您做到这一点.

My recommendation is to not do that, and instead learn how to work with geometry propagation. It will make your GUIs behave better when the user resizes the windows, and you won't be spending time trying to calculate the right size for a window. Let Tkinter do that for you.

这篇关于在Tkinter中向框架添加标签会忽略框架的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆