在tkinter python中执行“之后”脚本时如何处理无效的命令名称错误

问题描述

我知道这个问题在这里已经多次提出,我已经遍历了所有问题。但是我没有找到解决这个问题的明确方法。我知道发生此错误的原因。我知道在使用root.destroy()之后,仍然有一些工作需要完成,而所有这些工作。 但是我想知道如何停止那些“之后”的工作? 有人要求在代码中使用try / accept。但是他没有显示如何使用它。 因此,您能为这种情况提供一个明确的解决方案吗?有什么办法可以消除此错误? 我要求您不要将此问题标记为重复,请不要删除此问题。这很重要,我没有其他来源可以得到我的答案。

invalid command name "2272867821888time"
    while executing
"2272867821888time"
    ("after" script)

解决方法

在执行用after安排的回调之前销毁窗口时,会发生此错误。为避免此类问题,您可以存储在计划回调时返回的ID,并在销毁窗口时将其取消,例如使用protocol('WM_DELETE_WINDOW',quit_function)

这里是一个例子:

import tkinter as tk

def callback():
    global after_id
    var.set(var.get() + 1)
    after_id = root.after(500,callback)

def quit():
    """Cancel all scheduled callbacks and quit."""
    root.after_cancel(after_id)
    root.destroy()

root = tk.Tk()
root.pack_propagate(False)
var = tk.IntVar()
tk.Label(root,textvariable=var).pack()
callback()
root.protocol('WM_DELETE_WINDOW',quit)
root.mainloop()

此外,Tcl / Tk具有一个after info方法,该方法无法通过python包装器直接访问,但可以使用root.tk.eval('after info')进行调用,并返回ID字符串:'id1 id2 id3'。因此,跟踪所有ID的替代方法是使用以下方法:

import tkinter as tk

def callback():
    var.set(var.get() + 1)
    root.after(500,callback)

def quit():
    """Cancel all scheduled callbacks and quit."""
    for after_id in root.tk.eval('after info').split():
        root.after_cancel(after_id)
    root.destroy()

root = tk.Tk()
root.pack_propagate(False)
var = tk.IntVar()
tk.Label(root,quit)
root.mainloop()