【问题标题】:Check the size of tkinter window using "if" statement使用 \"if\" 语句检查 tkinter 窗口的大小
【发布时间】:2023-02-13 23:48:36
【问题描述】:

我想要一个 if 函数来检查 python (tkinter) 中窗口的几何形状。 这就是我所拥有的,但它不起作用:

 if root.geometry == "457x450":
    print("The window is 457x450 pixels!")

 else:
    print("The window is not 457x450!")

 

 root = Tk()
 root.geometry("300x300")

 root.mainloop()

在这种情况下,它应该打印“窗口不是 457x450!”

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    条件if root.geometry == "457x450": 永远不会为真。 root.geometry 是一种与字符串进行比较的绑定方法。您需要像 root.geometry() 一样调用它才能从 tkinter 检索几何字符串。

    然而几何字符串的形式是widthxheight+x+y 所以你的条件仍然不会变成True 即使你有正确的widthheight

    一个简单的方法是:
    if root.geometry().split('+')[0] == "457x450":

    【讨论】:

      【解决方案2】:

      您可以使用root.winfo_height()root.winfo_width()来查询当前窗口的宽度和高度(以像素为单位)。

      请注意,如果您在启动应用程序后立即调用这些方法(即通过调用root.mainloop()),您将得到错误的数字,因为窗口大小尚未确定,因此您应该调用root.update_idletasks()winfo_ 方法的调用!

      这应该是你想要的:

      root.update_idletasks()  # make sure the window is up to date
      width, height = root.winfo_width(), root.winfo_height  # get the window dimensions
      
      if (width, height) == (457, 450):
         print("The window is 457x450 pixels!")
      else:
         print("The window is not 457x450!")
      

      【讨论】:

        【解决方案3】:

        嗨,伙计们,我想通了!我只需要将窗口的实际大小存储在一个变量中....

        root = Tk()
        size = "304x450"
        root.geometry(size)
        root.mainloop()
        

        然后就说..

        if size == "457x450":
            print("Hello World")
        

        为我工作。如果我在函数中使用它,我只需要将变量全球化。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-04-21
          • 1970-01-01
          • 1970-01-01
          • 2017-04-08
          • 1970-01-01
          相关资源
          最近更新 更多