[英]How to handle Invalid command name error, while executing (“after” script) in tkinter python using OOP Approach
I have seen a lot of questions similar to mine on this thread however none of them are relatable to the OOP tkinter method that I am using.我在这个线程上看到了很多与我类似的问题,但是它们都与我使用的 OOP tkinter 方法无关。 I am getting the error:
我收到错误:
invalid command name "2452827444616callback"
while executing "2452827444616callback"
("after" script)
This happens because I am using the "after" function in a recursive loop but get this error whenever I close the tkinter window and try to open it back up again.发生这种情况是因为我在递归循环中使用了“after”函数,但是每当我关闭 tkinter 窗口并尝试再次打开它时都会收到此错误。
A simple example of my code structure which generates this problem is below:生成此问题的代码结构的一个简单示例如下:
import tkinter as tk
class MainApplication(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self._parent = parent
self.var = tk.IntVar()
tk.Label(self._parent, textvariable=self.var).pack()
self.callback() #This starts the recursion loop
def callback(self):
global after_id
self.var.set(self.var.get() + 1)
after_id = root.after(500, self.callback)
if __name__ == "__main__":
root = tk.Tk()
MainApplication(root).pack(side="top", fill="both", expand=True)
root.mainloop()
Similar issues have been solved like in this thread:类似的问题已在此线程中解决:
How to handle Invalid command name error, while executing ("after" script) in tkinter python 在 tkinter python 中执行(“after”脚本)时如何处理无效的命令名称错误
However, I cannot seem to get it to work due to the different structure that I am using with the OOP tkinter approach.但是,由于我在 OOP tkinter 方法中使用的结构不同,我似乎无法让它工作。 Any help would be greatly appreciated.
任何帮助将不胜感激。
You can cancel the after
task when the frame is being destroyed by calling after_cancel()
inside __del__()
function of MainApplication
class:您可以通过在
MainApplication
类的__del__()
函数中调用after_cancel()
来取消帧被销毁时的after
任务:
class MainApplication(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.var = tk.IntVar()
tk.Label(self, textvariable=self.var).pack()
self.callback() #This starts the recursion loop
def __del__(self):
self.after_cancel(self.after_id)
def callback(self):
self.var.set(self.var.get()+1)
self.after_id = self.after(500, self.callback)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.