![](/img/trans.png)
[英]Python how to link function if statements to Tkinter Label?
[英]Python - tkinter how to use if statements with get function?
我知道标题不是很容易理解,所以让我在这里解释一下。
基本上如果我这样做
if variable.get() == "Select Website":
print("ok")
它将打印出“确定”,但是如果我将其从“选择网站”更改为“费勒姆”,以及将下拉框中的选项更改为“费勒姆”,它不会注意到它已更改。 如果我希望它注意到它已更改,则需要执行一个while循环,但这首先会使脚本停止运行。
如果将变量更改为“ Fareham”,如何使脚本打印“确定”?
当前代码:
import tkinter
sites = [
"Fareham",
"Hants",
"Southampton",
"Eastleigh",
"Havant",
"Gosport",
]
win = tkinter.Tk()
win.geometry("500x500")
variable = tkinter.StringVar(win)
variable.set("Select Website")
drop = tkinter.OptionMenu(win, variable, *sites)
drop.pack()
if variable.get() == "Fareham":
print("ok")
win.mainloop()
在这里可以找到一些重要信息: http : //effbot.org/tkinterbook/variable.htm
通过将观察者设置为变量variable
,它将在每次更改时对其进行检查。
def check(*args):
if variable.get() == 'Fareham':
print 'ok'
variable.trace(
'w', # 'w' checks when a variable is written (aka changed)
check # this is the function it should call when the variable is changed
)
只需将代码替换您当前的if
语句,它就会像魅力一样工作。
您可以通过将回调函数与下拉菜单相关联来实现此目的:
import tkinter
def your_callback(*args):
if args[0] == "Fareham":
print("ok")
sites = [
"Fareham",
"Hants",
"Southampton",
"Eastleigh",
"Havant",
"Gosport",
]
win = tkinter.Tk()
win.geometry("500x500")
variable = tkinter.StringVar(win)
variable.set("Select Website")
drop = tkinter.OptionMenu(win, variable, *sites, command = your_callback)
drop.pack()
win.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.