Skip to content Skip to sidebar Skip to footer

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 occurre

Solution 1:

This error occurs when destroying the window before a callback scheduled with after is executed. 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).

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'. So an alternative to keeping track of all ids is to use this:

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

Post a Comment for "How To Handle Invalid Command Name Error, While Executing ("after" Script) In Tkinter Python"