Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

python - Adding label to frame in Tkinter ignores the attributes of frame

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...