53

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

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?

nbro
  • 15,395
  • 32
  • 113
  • 196
Johnston
  • 707
  • 2
  • 6
  • 8

1 Answers1

79

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

Since you are using pack the syntax would be:

f.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.

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.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • 1
    It could also be `self.pack_propagate(0)` if done in a method like the `__init__()` of a widget class derived from `Frame` -- as in the commonly used `class Application(Frame):` idiom. – martineau Sep 30 '12 at 19:09
  • The first example doesn't work for me. The window has the right size, but the widgets aren't visible on screen. The second example does work for me everything displays fine in the screen with the given width/height! +1 – Bas May 26 '15 at 19:30
  • @Bas: in the original example, the Frame "height" is not passed and defaults to 0, so when propagation is turned off, the height stays 0 and you don't see the Label. You would have to set the Frame height=20 or something along those lines to see the Label. – GaryMBloom Oct 22 '17 at 20:19
  • I get this problem when using place.what would I do? – GCIreland Oct 03 '22 at 15:10
  • @GCIreland: don't fully understand what you're asking. `place` won't cause this problem since `place` doesn't cause the parent widget geometry to be changed. It's irrelevant for this answer since the OP was specifically asking about using `pack`. – Bryan Oakley Oct 03 '22 at 15:40