Tkinter单选按钮动态加载图片报错问题求助
Tkinter单选按钮加载图片报错解决办法
问题描述
尝试在Tkinter的Radiobutton中使用列表项对应的图片,循环逻辑正常,但动态生成路径加载PhotoImage时出现错误。
原代码
from tkinter import * from PIL import Image, ImageTk win = Tk() win.title("Review demo") win.geometry("900x600") win.minsize(900, 600) win.maxsize(900, 600) choices = ["like", "dislike", "love", "garbage"] x = IntVar() img = StringVar() # 该声明无实际作用 for r in range(len(choices)): item_name = choices[r] path = item_name+".png" img = PhotoImage(file = path ) # img = PhotoImage(file = item_name+'.png') radiobtn = Radiobutton(win, text=item_name, variable=x, value=r, padx=20, pady=20, image= img ) radiobtn.pack(anchor=E) win.mainloop()
报错信息(翻译后)
img = PhotoImage(file = item_name+'.png') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Rohit\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 4130, in __init__ Image.__init__(self, 'photo', name, cnf, master, **kw) File "C:\Users\Rohit\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 4075, in __init__ self.tk.call(('image', 'create', imgtype, name,) + options) _tkinter.TclError: 无法识别图片文件"like.png"中的数据
解决办法
1. 确认图片有效性与路径
- 检查
like.png等文件是否和脚本在同一目录,若不在需使用绝对路径(如C:/project/images/like.png)。 - 确认图片未损坏,且Tkinter原生
PhotoImage支持该格式:它仅支持GIF、PGM、PPM以及部分版本的PNG,若图片是JPG等其他格式,必须用PIL库加载。
2. 改用PIL库加载图片
虽然导入了PIL,但代码仍使用Tkinter原生的PhotoImage,换成ImageTk.PhotoImage可支持更多图片格式,修改加载逻辑:
# 替换原img = PhotoImage(...)行 pil_img = Image.open(path) # 按需调整图片大小,示例为30x30 pil_img = pil_img.resize((30, 30), Image.Resampling.LANCZOS) img = ImageTk.PhotoImage(pil_img)
3. 避免图片对象被垃圾回收
循环中每次生成的img会被下一次迭代覆盖,且无引用绑定,Tkinter会自动回收图片对象,导致按钮不显示图片。需将图片对象绑定到单选按钮的属性上:
radiobtn.img = img
修改后的完整代码
from tkinter import * from PIL import Image, ImageTk win = Tk() win.title("Review demo") win.geometry("900x600") win.minsize(900, 600) win.maxsize(900, 600) choices = ["like", "dislike", "love", "garbage"] x = IntVar() for r in range(len(choices)): item_name = choices[r] path = item_name + ".png" # 使用PIL加载并调整图片大小 pil_img = Image.open(path) pil_img = pil_img.resize((30, 30), Image.Resampling.LANCZOS) img = ImageTk.PhotoImage(pil_img) radiobtn = Radiobutton(win, text=item_name, variable=x, value=r, padx=20, pady=20, image=img, compound=LEFT # 可选:设置图片与文字的排列位置 ) # 绑定图片对象到单选按钮,防止被垃圾回收 radiobtn.img = img radiobtn.pack(anchor=E) win.mainloop()
内容的提问来源于stack exchange,提问作者Rohit
相关产品推荐
相关产品推荐

