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

PIL Image无法读取同目录本地文件问题求助

问题描述

已将image.png与tray.py放在同一目录,但运行代码时,PIL的Image模块提示找不到该文件。

运行代码

import pystray
from PIL import Image
from importlib import reload
import os
import webbrowser

# Image for the tray
image = Image.open("image.png")

# Triggers for right click
def stop(icon, item):
    icon.stop()

def ss(icon, item):
    import discord

def edit(icon, item):
    os.system('config.json')

def git(icon, item):
    webbrowser.open('github')

def support(icon, item):
    webbrowser.open('discord')

# Buttons for right click
icon = pystray.Icon("Hydisc", image, menu=pystray.Menu(
    pystray.MenuItem("Start", ss),
    pystray.MenuItem("Edit Settings", edit),
    pystray.MenuItem("Github", git),
    pystray.MenuItem("Support", support),
    pystray.MenuItem("Quit", stop)
))

icon.run()

文件结构

  • 同一文件夹下包含两个文件:tray.py、image.png

报错信息

FileNotFoundError: [Errno 2] No such file or directory: 'image.png'

(附带PIL模块打开文件时的调用栈错误)

解决方案

问题出在相对路径的解析依赖当前工作目录,如果运行脚本时的工作目录不是脚本所在文件夹,就会找不到图片。可以通过获取脚本的绝对路径来拼接图片路径,确保定位准确:

修改代码中打开图片的部分:

# Image for the tray
# 获取脚本所在的绝对目录
script_dir = os.path.dirname(os.path.abspath(__file__))
# 拼接图片的绝对路径
image_path = os.path.join(script_dir, "image.png")
image = Image.open(image_path)

另外也可以检查:

  • 确认图片文件名完全一致,注意大小写(Linux/macOS系统区分文件名大小写)
  • 确认图片没有被误命名(比如后缀名被隐藏,实际是image.png.png)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:09:12