简体   繁体   English

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

[英]How to handle Invalid command name error, while executing (“after” script) in tkinter python

I know this question has been raised multiple times here and I have gone through all of them.我知道这个问题在这里被多次提出,而且我已经完成了所有这些问题。 But I didn't find a clear solution for the problem.但是我没有找到解决问题的明确方法。 I know the reasons for the occurrence of this error.我知道发生此错误的原因。 I know that after using root.destroy() , there are still some jobs left to be completed and all that stuff.我知道在使用root.destroy() ,还有一些工作需要完成以及所有这些东西。 But I want to know how to stop those "after" jobs?但我想知道如何停止那些“之后”的工作? One of the guys asked to use try / accept in the code.其中一个人要求在代码中使用try / accept But he didn't show how to use that.但他没有展示如何使用它。 So could you please give a clear solution for this case?那么您能否为这种情况提供明确的解决方案? Is there any way to remove this error?有什么办法可以消除这个错误吗? I request you not to mark this question duplicate and don't remove this question please.我要求您不要将此问题标记为重复,也不要删除此问题。 It's important and I don't have other sources to get my answer.这很重要,我没有其他来源可以得到我的答案。

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

This error occurs when destroying the window before a callback scheduled with after is executed. after执行after调度的回调之前销毁窗口时会发生此错误。 To avoid this kind of issue, you can store the id returned when scheduling the callback and cancel it when destroying the window, for instance using protocol('WM_DELETE_WINDOW', quit_function) .为了避免这种问题,您可以存储调度回调时返回的 id 并在销毁窗口时取消它,例如使用protocol('WM_DELETE_WINDOW', quit_function)

Here is an example:下面是一个例子:

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()

Also, Tcl/Tk has an after info method which is not directly accessible through the python wrapper but can be invoked using root.tk.eval('after info') and returns a string of ids: 'id1 id2 id3' .此外,Tcl/Tk 有一个after info方法,它不能通过 python 包装器直接访问,但可以使用root.tk.eval('after info')调用并返回一个 id 字符串: 'id1 id2 id3' So an alternative to keeping track of all ids is to use this:因此,跟踪所有 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, textvariable=var).pack()
callback()
root.protocol('WM_DELETE_WINDOW', quit)
root.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM