Tkinter为此提供了一个强大的工具,它被称为after。它旨在用作同步睡眠命令,但可以通过调用自身在mainloop内建立一个循环。
之后,是一个内置的Tcl命令,用于管理脚本的调度以供将来评估,还可以用作同步睡眠命令。
import tkinter as tk #import tkinterimport datetime #import datetime for our clockdef tick(): #function to update the clock showed_time = '' #current showed time current_time = datetime.datetime.now().strftime("%H:%M:%S") #real time if showed_time != current_time: #if the showed time is not the real time showed_time = current_time #update the variable to compare it next time again clock.configure(text=current_time) #update the label with the current time clock.after(1000, tick) #call yourself in 1000ms (1sec.) again to update the clock return Noneroot=tk.Tk()clock = tk.Label(root)clock.pack()tick()root.mainloop()在上面的脚本中,我们构建了一个数字时钟,并与after方法联系。after方法不过是一个时间间隔,在该时间间隔的结尾,我们希望发生一些事情。
要了解有关此基本窗口小部件方法的更多信息,请单击[click]
after(delay_ms,callback = None,args)
此方法注册一个 回调函数 ,该 函数 将在给定的毫秒数后调用 。Tkinter 只保证 不会早于回调被调用
;如果系统繁忙,则实际延迟可能会更长。
import tkinter as tk import datetimedef tick(): showed_time = '' current_time = datetime.datetime.now().strftime("%H:%M:%S") if showed_time != current_time: showed_time = current_time clock.configure(text=current_time) global alarm #make sure the alarm is known alarm = clock.after(1000, tick)#assign the alarm to a variable return Nonedef stop(): stop.after_cancel(alarm) #cancel alarmroot=tk.Tk()clock = tk.Label(root)clock.pack()stop = tk.Button(root, text='Stop it!', command=stop)stop.pack()tick()root.mainloop()在这里,我们具有相同的代码,但是可以使用tkinter方法 取消 循环
after_cancel。 您不需要在类中全局设置警报
。
self.alarm = self.clock.after(...)工作良好。
after_cancel(id)
取消告警回叫。
ID
告警标识。



