且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 tkinter 中的函数内调用函数

更新时间:2022-12-16 10:28:53

发生的事情是,每次调用 reset 时,都会启动一个新的 callback,它将调用start 无限期每 100 毫秒.每个回调都是独立的,并且不知道其他回调,这会导致一系列回调,每个回调在自己的时间调用 start,每 100 毫秒.

What is happening is that every time you call reset, a new callback is launched that will call start indefinitely every 100ms. Every callback being independent, and having no knowledge of the others, this results in a series of callbacks each calling start on their own time, every 100 ms.

为了避免这种滚雪球",您需要取消之前的回调才能正确重置.您可以通过保持对 callback 的引用,并在 reset 中调用 tk.after_cancel(callback_id) 来做到这一点.

To avoid this "snowballing", you need to cancel the previous callbacks in order to reset properly. You do this by keeping a reference on the callback, and calling tk.after_cancel(callback_id) in reset.

像这样:

import tkinter as tk


def start():
    global i, callback_id
    text_label.config(text=i)
    i += 1
    callback_id = text_label.after(1000, start)


def reset():
    global i, callback_id
    i = 0
    if callback_id is not None:
        text_label.after_cancel(callback_id)
        callback_id = None
    start()


window = tk.Tk()
window.geometry('400x400')

text_label = tk.Label(window, text="start")
text_label.pack()

callback_id, i = None, 0
tk.Button(window, text="reset", command=reset).pack()

window.mainloop()