您可以使用after(time_ms, function_name)
反复(但不while True
)调用你的函数。
import Tkinter as tk
# --- functions ---
def check():
if status != 1:
print 'check:', status
# check again after 100ms
master.after(100, check) # filename without()
def callback():
global status # because you use `=`
status = 0
print 'callback:', status
# --- main ---
status = 1
master = tk.Tk()
myB = tk.Button(master, text="Enter", command=callback)
myB.pack()
# check after 100ms
master.after(100, check) # filename without()
# or call immediately
# check()
tk.mainloop()
或者您可以使用对象IntVar
,StringVar
等,trace
调用函数时,对象的变化值。
此外,Label
可以在StringVar
更改值时自动更改文本 - 它不需要trace
。
import Tkinter as tk
# --- functions ---
def check(arg1, arg2, arg3): # 3 args always send by `trace`
print 'check:', status.get() # always use `get`
def callback():
# no needed `global status`
status.set(0) # always use `set` instead of `=`
print 'callback:', status.get() # always use `get`
# --- main ---
master = tk.Tk()
status = tk.IntVar() # now always use get(), set()
status.set(1)
status.trace('w', check) # w - write (`set` was used)
# use IntVar in Label
l = tk.Label(master, textvariable=status)
l.pack()
b = tk.Button(master, text="Enter", command=callback)
b.pack()
tk.mainloop()
见:The Variable Classes (BooleanVar, DoubleVar, IntVar, StringVar)
'主循环()'启动程序并运行,直到你关闭程序。您不能在Tkinter(或其他GUI)中使用'while循环','睡眠'或其他长时间运行的函数。 – furas
@furas - 谢谢。 是否有另一种方法来“聆听”变量的变化? – user3092118
您可以使用'tkinter.IntVar'来创建特殊的对象变量a,然后使用'trace'在该对象更改值时调用函数。 – furas