Tkinter无法显示图片且无报错问题求助
问题排查与修复方案
核心错误点
你的代码存在两处关键问题导致图片无法显示:
- 图片引用保存错误:创建
img_tk(ImageTk.PhotoImage对象)后,错误地将PIL的photo对象赋值给image_label.image,Python垃圾回收机制会回收未被引用的img_tk,导致图片无法渲染。 - 异常块语法错误:
default_image已经是ImageTk.PhotoImage对象,不需要追加.gif后缀,这会引发属性错误(若未触发异常则不会报错,但逻辑无效)。
修复后的代码
def show_restaurant_info(event): selected_restaurant = restaurant_listbox.get(tk.ACTIVE) if selected_restaurant: restaurant = next((r for r in restaurants if r["name"] == selected_restaurant), None) if restaurant: info_label.delete('1.0', tk.END) restaurant_name = restaurant["name"] restaurant_postal_code = restaurant["postal_code"] restaurant_cuisine = restaurant["cuisine"] restaurant_price = restaurant["price"] restaurant_reviews = restaurant["reviews"] # 显示餐厅信息 info_label.insert(tk.END, f"""Name: {restaurant_name} Postal Code: {restaurant_postal_code} Cuisine: {restaurant_cuisine} Price: {restaurant_price} Reviews: {restaurant_reviews} """) # 加载并显示餐厅图片 image_path = restaurant["image"] try: photo = Image.open(image_path) photo = photo.resize((50, 50)) img_tk = ImageTk.PhotoImage(photo) image_label.configure(image=img_tk) # 必须保存ImageTk对象引用,防止被垃圾回收 image_label.image = img_tk except (IOError, tk.TclError): # 加载失败时显示默认图片 default_image = ImageTk.PhotoImage(Image.open("default_image.gif")) image_label.configure(image=default_image) image_label.image = default_image
额外注意事项
- 确认
image_path是正确的文件路径(相对路径需与脚本运行目录匹配,使用绝对路径更可靠) - 确保
default_image.gif存在于指定路径 - 原代码中的全局变量
photo无实际作用,可直接删除
内容的提问来源于stack exchange,提问作者Monil Shah
相关产品推荐
相关产品推荐

