求助:Python Tkinter Image函数无法定位PNG文件的问题
问题排查与解决方案
核心原因
你使用的是Tkinter自带的PhotoImage(代码中因from tkinter import *简写为Image),它默认仅支持GIF、PGM、PPM格式,不支持PNG,这就是报错提示"image type 'xxx.png' doesn't exist"的根本原因。
解决步骤
安装Pillow库
Pillow是PIL的分支,支持包括PNG在内的绝大多数图像格式,执行以下命令安装:pip install pillow修改代码
调整导入逻辑和图像加载代码,同时注意保留图像对象的引用(避免被Python垃圾回收导致图像不显示):from tkinter import * from tkinter import filedialog import os import sys # 新增Pillow相关导入 from PIL import Image, ImageTk temp_table = [("a","Answer is a because A",r"assets\q1g.png"), # 用原始字符串避免转义问题 ("c","C is the answer",r"assets\q2g.png"), ("d","D is the answer",r"assets\q3g.png")] current_placard = 0 def resource_path(relative_path): """ Get the absolute path to a resource, works for dev and for PyInstaller """ try: base_path = sys._MEIPASS except AttributeError: base_path = os.path.dirname(os.path.abspath(__file__)) return os.path.join(base_path, relative_path) # 其余函数(load_quiz_file)保持不变 def previous_slide(): global current_placard if current_placard > 0: current_placard -= 1 answer,explain,graphic = temp_table[current_placard] # 修改图像加载逻辑 img = Image.open(resource_path(graphic)) temp_graphic = ImageTk.PhotoImage(img) # 将图像对象绑定到label_q的属性,保留引用 label_q.image = temp_graphic label_q.config(image=temp_graphic) window = Tk() label_q = Label(window, height=23, background="red",text="Question placard will be displayed here.") label_q.pack(fill=X,expand=True) previous_slide() window.mainloop()
额外注意事项
- 确保PNG文件确实存在于
assets目录下,可在代码中加入print(resource_path(graphic))再次验证路径正确性。 - 如果用PyInstaller打包,需要将assets目录中的PNG文件一并打包,可通过添加
--add-data参数实现,例如:pyinstaller --add-data "assets/*.png;assets" problematic.py
内容的提问来源于stack exchange,提问作者JHCode
相关产品推荐
相关产品推荐

