views:

51

answers:

1

With this code, the window is 500 by 500, which is what I'm going for:

from tkinter import *
root = Tk()

frame = Frame(root, width=500, height=500)

frame.pack()
root.mainloop()

When I add a text box to the frame, though, it shrinks to just the size of the text box:

from tkinter import *
root = Tk()

frame = Frame(root, width=500, height=500)

text = Text(frame, width=10, height=2) # THESE TWO
text.pack()                            # LINES HERE

frame.pack()
root.mainloop()

Why does this happen, and how can I prevent it from happening?

+2  A: 

The frame by default has "pack propagation" turned on. That means the packer "computes how large a master must be to just exactly meet the needs of its slaves, and it sets the requested width and height of the master to these dimensions" (quoting from the official tcl/tk man pages [1]).

For the vast majority of cases this is the exact right behavior. For the times that you don't want this you can call pack_propagate on the master and set the value to false. I think in close to 20 years of tk programing I've only needed to do this a half dozen times or so, if that.

Another choice you have is to use wm_geometry to set the size of the toplevel after you've created all the widgets. This does effectively the same thing as if the user had manually resized the window. This only works for toplevel windows though, you can't use wm_geometry on a frame.

Bryan Oakley
Wonderful, thanks very much!
Kiwi