Invalid command name while executing ("after" script) Invalid command name while executing ("after" script) tkinter tkinter

Invalid command name while executing ("after" script)


If you destroy the window, whatever "after" jobs that have already been scheduled may run. If the window is destroyed and this job interacts with a widget that has been deleted, you'll get this error.

You can either put a try around the code and ignore such an error, check that the window exists before trying to configure it, or put a handler in for when the main window is destroyed to delete any pending "after" jobs.


Background

I was getting these 'errors' as well. They're not actual exceptions, they're just annoying to see being spammed in the terminal when running unittests.

I had tried a lot of things, including overriding the after method in tkinter.Tk to keep track of any queued methods and then calling tkinter.Tk.after_cancel() automatically before calling tkinter.Tk.destroy() as @GabrielStaples commented.

So I was getting these errors even though there were no queued after methods at the point of destroy() being called.

My solution

What worked for me was calling tkinter.Tk.quit() to destroy the window instead of destroy(). I read that quit() doesn't stop the mainloop but it seems fine. Any methods queued by after aren't called after quit() has been called.

Perhaps somebody could explain any consequences I'm not aware of if there are any


I had this problem because my module was named "setup" and I also had a setup.py file. When calling setup.py somecommand, you will get "invalid command name 'somecommand'".