python-3.x - while 循环和使用 after 重复调用函数的区别

标签 python-3.x recursion tkinter while-loop

有什么区别

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/

相关文章:

python 3 : How to use a type defined later for Function Annotations?

c - 如何从递归中的函数编辑指向列表节点的指针?

c++ - 如何在不使用任何循环的情况下在 C++ 中使用 * 打印 X 形状

c# - 返回多个文件夹的文件列表的最有效方法

algorithm - 将成对距离映射到二维空间的领域或算法类的名称是什么?

python-3.x - 如果条件,则返回语句在 python 中不起作用

python - 排除 Python 键入注释中的类型

python - 滚动条滚动文本小部件,使用网格布局,在 Tkinter

python - 如何从 tkinter 中的绑定(bind)回调中获取回调引用?

python - tkinter 照片图像构造函数