_tkinter.TclError: can't invoke "menu" command: application has been destroyed

我在做一个.py文件时报了错:_tkinter.TclError: can't invoke "menu" command: application has been destroyed.

发生异常: TclError
can't invoke "menu" command: application has been destroyed
  File "C:\Users\Administrator\Desktop\a\a.py", line 11, in __init__
    m1=ttk.Menu(root,tearoff=False)
  File "C:\Users\Administrator\Desktop\a\a.py", line 61, in <module>
    init.__init__()
_tkinter.TclError: can't invoke "menu" command: application has been destroyed

但是报错前运行的好好的,关闭窗口后就出现了。

python版本:3.8.6 64-bit
编辑器:vscode

该回答引用ChatGPT

这个错误通常是由于关闭了Tkinter应用程序的窗口后,尝试访问已被销毁的对象而引起的。具体来说,在您的代码中,当您关闭窗口时,Tkinter对象已被销毁,但是您的程序仍在尝试访问其中的某些对象,例如菜单栏对象。

解决这个问题的方法是,您可以在窗口关闭时,将所有Tkinter对象一并销毁。在您的代码中,可以通过添加以下代码来实现:


root.protocol("WM_DELETE_WINDOW", root.quit)  # 设置关闭窗口时销毁Tkinter对象

该代码会将窗口的关闭事件与 root.quit 函数绑定,当窗口关闭时,会自动执行该函数来销毁所有Tkinter对象。

您可以将其添加到程序的初始化函数中,如下所示:


class init:
    def __init__(self):
        self.root=Tk()
        self.root.geometry('500x500')
        self.root.title('窗口')
        
        m1=ttk.Menu(root,tearoff=False)
        root.config(menu=m1)
        file=ttk.Menu(m1,tearoff=False)
        m1.add_cascade(label='文件',menu=file)
        file.add_command(label='打开')
        file.add_command(label='保存')
        
        root.protocol("WM_DELETE_WINDOW", root.quit)  # 添加这行代码

        self.root.mainloop()

init().__init__()

这样,当您关闭窗口时,所有的Tkinter对象都会被销毁,避免了在已被销毁的对象上尝试调用方法而引起的异常。