我想使用倒数计时器功能在Tkinter中设置标签。现在,一旦达到10,我所做的全部工作就是将标签设置为“ 10”,我真的不明白为什么。另外,即使我将计时器打印到终端上,“时间到了!” 一点都不打印。
import time import tkinter as tk class App(): def __init__(self): self.root = tk.Tk() self.label = tk.Label(text="null") self.label.pack() self.countdown() self.root.mainloop() # Define a timer. def countdown(self): p = 10.00 t = time.time() n = 0 # Loop while the number of seconds is less than the integer defined in "p" while n - t < p: n = time.time() if n == t + p: self.label.configure(text="Time's up!") else: self.label.configure(text=round(n - t)) app=App()
Tkinter已经有一个无限循环运行(事件循环),并且有一种方法可以安排在一段时间后运行事物(使用after)。您可以通过编写每秒调用一次以更新显示的函数来利用此功能。您可以使用类变量来跟踪剩余时间。
after
import Tkinter as tk class ExampleApp(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.label = tk.Label(self, text="", width=10) self.label.pack() self.remaining = 0 self.countdown(10) def countdown(self, remaining = None): if remaining is not None: self.remaining = remaining if self.remaining <= 0: self.label.configure(text="time's up!") else: self.label.configure(text="%d" % self.remaining) self.remaining = self.remaining - 1 self.after(1000, self.countdown) if __name__ == "__main__": app = ExampleApp() app.mainloop()