![](/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.