简体   繁体   中英

python Tkinter: how to disallow a window growing bigger than screen size

My routine adds buttons to a window in tkinter. At some point the window becomes bigger (in height) than my actual screen and I cannot access the buttons at the bottom anymore.

Demo code:

from Tkinter import *

n_buttons = 20 # <- change this as you wish for testing the code

def generate_buttons(n):

    for i in range(n):
        button = Button(myframe, text="Button Clone", height=4)
        button.grid(row=i)

root = Tk()
myframe = Frame(root)
myframe.pack()

generate_buttons(n=n_buttons)

root.mainloop()

As a first attempt, I placed the following code into my loop:

if root.winfo_height() > root.winfo_screenheight():
    print("I'm full!")
    break

But 1) it does not work and 2) I'd strongly prefer a solution that checks if the window can take another button before it is created, so that I do not have to destroy it afterwards.

In my real code the buttons a placed as a 2D-grid and my first reaction to an overload of my window would be to increase the number of columns in my frame and then to reduce the height of all buttons. Again, it would be bad if I had to re-generate all buttons until all requirements are met. It would be great if you could help me with a solution that checks if the geometry is possible, before the first button is created. Thanks!

It's difficult to know if a widget will fit since there are so many variables. For example, padding, margins, other widgets on the screen, etc.

That being said, since you know your own application you can account for that. The only thing that's missing is knowing how tall a button is. You can get that from tkinter with the winfo_reqheight and winfo_reqwidth methods which return the height and width requested by the button. Then, it's just a matter of math.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM