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

MacBook环境下Python程序无法加载同目录图片文件求助

解决PhotoImage无法加载同目录图片的问题

针对你遇到的图片找不到问题,从几个常见方向排查解决:

1. 确保脚本工作目录与图片路径一致

有时候运行脚本的工作目录并非脚本所在目录,导致相对路径失效。可以通过脚本绝对路径拼接图片路径:

import os
# 获取当前脚本所在目录
script_dir = os.path.dirname(os.path.abspath(__file__))
# 拼接图片的绝对路径
img_path = os.path.join(script_dir, "App1.png")
img1 = PhotoImage(file=img_path)

2. 避免PhotoImage被垃圾回收

Tkinter的PhotoImage对象如果没有被持续引用,会被Python垃圾回收机制清理,表现为图片无法显示(类似找不到文件)。需要给标签绑定图片引用:

img1_label = customtkinter.CTkLabel(app, image=img1, text="Fermented Tea Leaves Salad\n A refreshing and tangy salad with fermented tea leaves. \n Price: $8.50",font=font2, text_color="Black", fg_color="Pink", width=200, height=200, corner_radius=20, compound= TOP,anchor=N)
# 保留图片引用,防止被回收
img1_label.image = img1

3. 处理图片格式兼容性问题

原生PhotoImage仅支持有限格式(GIF、PNG、PGM/PPM),如果图片格式不兼容或损坏,也会触发找不到文件的错误。可以用PIL库扩展支持:

  1. 先安装依赖:
pip install pillow
  1. 修改图片加载代码:
from PIL import Image, ImageTk

# 加载图片
img = Image.open("App1.png")
# 转换为Tkinter可用的格式
img1 = ImageTk.PhotoImage(img)
# 同样需要保留引用
img1_label = customtkinter.CTkLabel(app, image=img1, text="Fermented Tea Leaves Salad\n A refreshing and tangy salad with fermented tea leaves. \n Price: $8.50",font=font2, text_color="Black", fg_color="Pink", width=200, height=200, corner_radius=20, compound= TOP,anchor=N)
img1_label.image = img1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 08:15:08