有什么区别
def after_func():
while True:
now_time.configure(text=datetime.datetime.now().strftime('%H: %M: %S'))
time.sleep(1)
root = Tk()
now_time = Label(text=datetime.datetime.now().strftime('%H: %M: %S'))
now_time.pack()
root.after(10, after_func)
root.mainloop()
和
def after_func():
now_time.configure(text=datetime.datetime.now().strftime('%H: %M: %S'))
root.after(1000, after_func)
root = Tk()
now_time = Label(text=datetime.datetime.now().strftime('%H: %M: %S'))
now_time.pack()
root.after(10, after_func)
root.mainloop()
为什么第一个给出一个没有响应的消息而第二个导致时钟每秒更新一次?在我看来,这两个代码应该产生相同的结果。
最佳答案
关键区别在于使用 root.after
的代码允许事件循环 (mainloop
) 在每次迭代之间处理事件。 while
循环没有。 Tkinter 应用程序几乎所有的事情都依赖于事件循环,包括来自操作系统或应用程序本身的请求,当它检测到应该显示的内容发生变化时重新绘制窗口。
通过在循环内调用 root.update
,您可以几乎获得与 while
循环相同的结果,但不推荐这样做。另外,sleep
的使用正如其名称所暗示的那样:整个程序进入休眠状态一秒钟。在那一秒内,您的应用将变得完全没有响应。
从技术上讲,带有after
的版本不是递归的。它所做的只是将自己放在队列中以供稍后调用。调用堆栈不会变大。
关于python-3.x - while 循环和使用 after 重复调用函数的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63507975/