You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python的Tkinter显示图片报错:TclError: image "pyimage21"不存在

Tkinter报错TclError: image "pyimage21" doesn't exist的解决办法

这个报错的核心原因是Tkinter的PhotoImage对象被Python垃圾回收机制回收了——当你创建photo变量后,没有让它和界面元素(比如Label)保持绑定,Python会认为这个对象不再被使用,就会释放它,导致Tk找不到对应的图片资源。

解决步骤:

  • 给PhotoImage对象添加持久引用,最直接的方式是把它绑定到Label组件的属性上
  • 确认图片路径正确、文件实际存在,且格式为Tkinter支持的类型(比如PNG、GIF,不支持JPG,处理JPG需要借助PIL库)

修正后的代码:

import tkinter as tk

root = tk.Tk()
root.geometry("500x500")
root.title("Poker ranges")

photo = tk.PhotoImage(file="C:\\Users\\chaeh\\OneDrive\\Desktop\\poker\\hand_range_grid.png")
text = tk.Label(root, image=photo)
# 绑定photo到Label属性,防止被垃圾回收
text.image = photo
text.pack()  # 将Label添加到窗口,否则无法显示
root.mainloop()

额外注意:如果代码中意外创建了多个tk.Tk()实例,也会触发该报错,确保整个程序只存在一个主窗口实例。

内容的提问来源于stack exchange,提问作者Jonathan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 11:10:53