英文:
Check the size of tkinter window using "if" statement
问题
if root.geometry == "457x450":
print("窗口大小为457x450像素!")
else:
print("窗口大小不是457x450!")
英文:
I want an if-function to check the geometry of a window in python (tkinter).
This is what I've got, but it doesn't work:
if root.geometry == "457x450":
print("The window is 457x450 pixels!")
else:
print("The window is not 457x450!")
root = Tk()
root.geometry("300x300")
root.mainloop()
In this case it should print "The window is not 457x450!"
答案1
得分: 3
以下是翻译好的部分:
条件 if root.geometry == "457x450":
将永远不会为真。 root.geometry
是一个绑定的方法,你将其与一个字符串进行比较。你需要像这样调用它 root.geometry()
以从 tkinter 中检索几何字符串。
然而,几何字符串的格式是 widthxheight+x+y
,所以即使你拥有正确的 width
和 height
,你的条件仍然不会变为 True
。
一个简单的方法是:
if root.geometry().split('+')[0] == "457x450":
英文:
The condition if root.geometry == "457x450":
will never be true. root.geometry
is a bound method that you compare to a string. You will need to call it like root.geometry()
to retrieve the geometry string from tkinter.
However a geometry string has the form of widthxheight+x+y
So your condition will still not turn to True
even you have the right width
and height
.
A simple way of doing it would be:
if root.geometry().split('+')[0] == "457x450":
答案2
得分: 1
你可以使用 root.winfo_height()
和 root.winfo_width()
来查询窗口的当前宽度和高度(以像素为单位)。
请注意,如果在启动应用程序后立即调用这些方法(即通过调用 root.mainloop()
),你将得到错误的数字,因为窗口尺寸尚未建立,所以在调用 winfo_
方法之前应该调用 root.update_idletasks()
!
这应该是你想要的效果:
root.update_idletasks() # 确保窗口已更新
width, height = root.winfo_width(), root.winfo_height() # 获取窗口尺寸
if (width, height) == (457, 450):
print("窗口尺寸为 457x450 像素!")
else:
print("窗口尺寸不是 457x450 像素!")
英文:
You can use root.winfo_height()
and root.winfo_width()
to query the current width and height of the window in pixels.
Note that if you call these methods immediately after starting your app (i.e., by calling root.mainloop()
) you'll get erroneous numbers because the window size hasn't been established yet, so you should call root.update_idletasks()
before the call(s) to the winfo_
methods!
This should to what you want:
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
得分: 0
Hi guys,我弄清楚了!我只需要将窗口的实际大小存储在一个变量中...
root = Tk()
size = "304x450"
root.geometry(size)
root.mainloop()
然后只需说...
if size == "457x450":
print("Hello World")
对我来说有效。如果我在函数中使用它,我只需将变量全局化。
英文:
Hi guys I figured it out! I just have to store the actual size of the window in a variable....
root = Tk()
size = "304x450"
root.geometry(size)
root.mainloop()
and then just say..
if size == "457x450":
print("Hello World")
Worked for me. I just had to globalize the variable if I'm using it in a function.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论