Window too small

Question:

Here is the code:

from Tkinter import *

def main():
    w1 = Tk()
    w1["height"] = 400;
    w1["width"] = 500;
    w1.title("Gui")
    f1 = Frame(w1)
    f1.grid_propagate()
    f1["height"] = w1["height"];
    f1["width"] = w1["width"];
    f1.pack()
    p1 = Button(f1)
    p1["borderwidth"] = 6
    p1["text"] = "esci"
    p1["background"] = "red"
    p1["command"] = f1.quit
    p1.pack()
    w1.mainloop()
main()

I have given to w1 and f1 (window and frame) a 500×400 size, but a too small window appears: it’s too small, I would say 200×100, but I don’t know … why does this happen?

Asked By: Ramy Al Zuhouri

||

Answers:

You need to use

f1.pack_propagate(0)

so that it doesn’t shrink

Answered By: Abhijeet Rastogi

It is this small because tkinter windows by default “shrink to fit”. This is called geometry propagation, and it seems like you might already be familiar with it because you call grid_propagate — though, without having it actually do anything and without using what it returns.

There are actually two problems in your code. The first is that you call f1.grid_propagate(), but you are using pack to arrange the widgets in f1 so you need to call f1.pack_propagate instead. Second, you need to pass a flag of False to actually turn off propagation. Doing that will prevent f1 from shrinking to fit its contents.

Second, you aren’t turning propagation off on w1, so it will shrink to fit its children. You either need to call w1.grid_propagate(False), OR you can call w1.wm_geometry("500x400") to request that the window manager set the size to that exact dimension.

If you are just learning Tkinter, I suggest you resist the urge to turn propagation off. In my couple dozen years of coding in tk I’ve used that feature maybe once every couple of years. Tkinter’s geometry managers are remarkable tools and you should learn to take advantage of them. Instead of having containers control their size, let the children be the size you want them to be and the rest of the GUI will work just fine.

Answered By: Bryan Oakley
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.