0

我在我的 tkinter 代码中使用了 'after' 函数,如下所示:

def task():
     #some work
     root.after(1000, task)
root.after(1000, task)

我想知道 task() 函数在到达 root.after() 行后是否会保留在那里,或者它会在到达该行后结束。

我是 python 和 tkinter 的新手,所以对发生了什么有点好奇。

提前致谢。

4

1 回答 1

3

它不会,因为task()调用Tk.after()会在内部注册回调并且不会导致延迟。之后task()就存在了。

例如(Python3):

import tkinter as tk

root = tk.Tk()

TIMEOUT = 3000
i = 0
def task():
    global i
    i += 1
    print('In task(), i={}'.format(i))
    root.after(TIMEOUT, task)
    print('Called root.after() and exiting task()')


root.after(TIMEOUT, task)
root.mainloop()

输出是:

In task(), i=1
Called root.after() and exiting task()
In task(), i=2
Called root.after() and exiting task()
In task(), i=3
Called root.after() and exiting task()

如果您运行代码,您会注意到这'Called root.after() and exiting task()'会立即发生。

于 2013-03-14T09:57:47.953 回答