我尝试在 tkinter 的菜单按钮中使用照片图像..
程序运行正确..
但是。
当我关上窗户时..
出现此错误:
Exception ignored in: <function Image.__del__ at 0x028AF028>
Traceback (most recent call last):
File "E:\programming\Python38-32\lib\tkinter\__init__.py", line 4018, in __del__
TypeError: catching classes that do not inherit from BaseException is not allowed
有错误的代码:
import tkinter as tk
root = tk.Tk()
toolbar = tk.Frame(root)
toolbar_menu_icon = tk.PhotoImage(file = "./icon.png")
toolbar_menu = tk.Button(toolbar, image=toolbar_menu_icon)
toolbar_menu.pack()
toolbar.pack()
root.mainloop()
我必须从
__init__.py
修改
PYTHON_PATH/Lib/tkinter/__init__.py
并将第 4018 行替换为:
except Exception:
和以前一样:
except TclError
这确保了除了任何例外,这都会起作用..
我使用 Ubuntu 23.10 时遇到同样的老问题,使用其系统 Python 3.11.6,其中包含 Tkinter 8.6。这个问题似乎是一个老错误,开发人员认为他们已经在 2014 年修复了:
https://github.com/python/cpython/issues/62341
因此全局变量按照错误的顺序被销毁。好吧,窗口关闭事件与 root.destroy() 而不是 root.quit() 相关联,因此将其与 root.quit() 关联可以防止出现错误消息。已修复。
哦等等,这会导致一个新问题。如果您在基于 Tkinter 的 IDE(例如 IDLE)中运行 Python,那么您会发现根本无法关闭窗口,因为 IDLE 使 Tkinter 保持活动状态。因此,在 root.mainloop() 之后添加更多行以首先删除照片图像,然后使用 root.destroy() 销毁所有其余内容。不过,阻止错误消息很麻烦。 所以这是上面问题的代码,加上了这些额外的行:
import tkinter as tk
root = tk.Tk()
toolbar = tk.Frame(root)
toolbar_menu_icon = tk.PhotoImage(width=300,height=100)
toolbar_menu = tk.Button(toolbar, image=toolbar_menu_icon)
toolbar_menu.pack()
toolbar.pack()
root.protocol("WM_DELETE_WINDOW", root.quit)
root.mainloop()
del toolbar_menu_icon
root.destroy()