使用Tkinter开发自动化界面时突发“pyimage2不存在”错误
Tkinter报错:
image "pyimage2" doesn't exist 排查与解决 问题背景
用Tkinter开发自动化界面,昨日代码运行正常,今日突然抛出错误:_tkinter.TclError: image "pyimage2" doesn't exist
报错回溯
# python3 app.py Traceback (most recent call last): File "/root/QT/CodTubify/src/app.py", line 163, in <module> image_1 = canvas.create_image( File "/usr/lib/python3.10/tkinter/__init__.py", line 2819, in create_image return self._create('image', args, kw) File "/usr/lib/python3.10/tkinter/__init__.py", line 2805, in _create return self.tk.getint(self.tk.call( _tkinter.TclError: image "pyimage2" doesn't exist
核心代码片段
window = Tk() window.title("ExLog") window.geometry("1092x506") window.configure(bg = "#171435") '''for custom cursor''' #cursor_path=relative_to_assets("@Busy.ani") #window['cursor']=cursor=cursor_path '''For Custom title bar''' #window.overrideredirect(1) #window.wm_attributes("-transparentcolor","#35F331") '''For Icon''' #window.iconbitmap(relative_to_assets("icon2.ico")) #메인 프레임 image_file = PhotoImage(file='./gui/Primary_Window/assets/image_1.png') # 'image_path.png'를 실제 이미지 파일 경로로 교체해야 합니다. canvas = Canvas( window, bg = "#494B69", height = 506, width = 930, bd = 0, highlightthickness = 0, relief = "ridge" ) canvas.place(x = 0, y = 0) background_image = PhotoImage( file=relative_to_assets("image_1.png")) image_1 = canvas.create_image( 566.0, 253.0, image=background_image, anchor='nw' )
原因分析
- 垃圾回收销毁图像对象:Tkinter的
PhotoImage如果没有被全局变量或父窗口等对象持有引用,会被Python垃圾回收器清理,导致Tkinter找不到对应图像资源。代码里的background_image是局部变量,很容易被回收。 - 重复创建图像实例冲突:代码里同时创建了
image_file和background_image两个指向同一张图的PhotoImage实例,可能触发Tkinter内部图像ID的冲突(pyimage2是第二个实例的ID)。 - 路径加载失败:
relative_to_assets函数返回的路径可能出错,导致background_image实际没加载成功,但代码仍尝试引用这个不存在的图像ID。
解决方法
- 保留图像对象的引用
把background_image绑定到窗口对象上,避免被垃圾回收:
# 将background_image赋值给window的属性,持久化引用 window.background_image = PhotoImage(file=relative_to_assets("image_1.png")) image_1 = canvas.create_image( 566.0, 253.0, image=window.background_image, anchor='nw' )
- 复用已加载的图像实例
既然已经加载了image_file,直接复用即可,不用重复创建:
# 删除background_image的重复创建代码,直接使用已有的image_file image_1 = canvas.create_image( 566.0, 253.0, image=image_file, anchor='nw' )
- 验证图像路径正确性
打印relative_to_assets返回的路径,确认是否指向正确的文件:
path = relative_to_assets("image_1.png") print(path) # 检查输出路径是否存在、拼写正确 background_image = PhotoImage(file=path)
内容的提问来源于stack exchange,提问作者삐야깐따
相关产品推荐
相关产品推荐

