George
George

Reputation: 4674

tkinter's .pack_propagate() method

I am experimenting with Tkinter, as I was trying to figure out is there a way to set the tkinter's window size without using canvas. I came upon this how to set frame size question on SO's Question & Answer. So I went ahead and test it by writing a very small program to display a text label. But I found out it is "missing", or disappear when I use frame.pack_propagate(0)

import tkinter as tk

root = tk.Tk()
frame = tk.Frame(root, width=400, height=400)
# Does not work at the moment, textBox is missing
# frame.pack_propagate(0) 
frame.pack()

textBox = tk.Label(frame, text="(x,y): ")
textBox.pack()

root.mainloop()

So my question is, can you explain why my textBox (Label) is not appearing when I use the frame.pack_propagate(0) instead of frame.pack() method? And secondly, is there a way to set the window size without using a canvas? I want to know because I am writing a series of small programs to teach my friend about tkinter, before introducing canvas to him. It would be nice if the window size are all the same across my tkinter samples. And I am just wondering as well (curious). Thank you very much.

I am using python 3.2.2 on MAC OS 10.5.8.

Upvotes: 4

Views: 24428

Answers (2)

Nummer_42O
Nummer_42O

Reputation: 433

To answer your second question: Yeah, there is a way.

tkinters Tk do have the Tk.geometry function. When you just call it without arguments, you will get the current geometry in form of 'widthxheight+x+y', so for example (on Windows 10) '200x200+26+26' when you create your first Tk window. Using that format you can resize the Tk by, e.g., writing: root.geometry('400x500+60+60') to set the width to 400, the height to 500 and place it at the coordinates (60|60).

This works for Tk alswell as for Toplevel. But Toplevel also takes the arguments height and width when initialized or configured. If you want them to keep their size when packing something inside just use root.pack_propagate(False) on them.

By the way there is something similar for the grid manager: root.grid_propagate(False)

Upvotes: 3

Bryan Oakley
Bryan Oakley

Reputation: 385840

pack_propagate only sets a flag, it doesn't cause the frame to be placed in the widget. It is not a substitute for calling pack.

In other words you must do this:

# put the frame in its parent
frame.pack()

# tell frame not to let its children control its size
frame.pack_propagate(0)

# put the textbox in the frame
textBox.pack()

Upvotes: 13

Related Questions