简体   繁体   English

python Tkinter:如何不允许窗口大于屏幕大小

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

My routine adds buttons to a window in tkinter. 我的例程在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. 但是1)它不起作用,2)我强烈希望使用一种解决方案, 创建窗口之前检查窗口是否可以使用另一个按钮,这样我以后就不必销毁它了。

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. 在我的真实代码中,按钮作为2D网格放置,我对窗口超载的第一反应是增加框架中的列数,然后减小所有按钮的高度。 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. 您可以使用winfo_reqheightwinfo_reqwidth方法从winfo_reqheight获得该方法,这些方法返回按钮请求的高度和宽度。 Then, it's just a matter of math. 然后,这只是数学问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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