Windows11下PyInstaller打包Python程序后找不到solarpic.gif的问题求助
PyInstaller打包后无法找到图片文件的解决方案
环境信息
- Windows 11
- Python 3.8.10
- PyInstaller打包单文件窗口程序
打包操作
我执行的打包命令:
pyinstaller --onefile --windowed --add-data "solarpic.gif;." scratch.py
solarpic.gif与scratch.py处于同一目录。
报错情况
运行打包后的程序时出现如下错误:
Traceback (most recent call last): File "scratch.py", line 7, in <module> File "PIL\Image.py", line 3227, in open FileNotFoundError: [Errno 2] No such file or directory: 'solarpic.gif'
原代码
scratch.py内容:
from tkinter import * from PIL import ImageTk, Image root=Tk() picframe = LabelFrame(root) picframe.grid(column=0, row=0, padx=10, pady=10,sticky=NSEW) photo_image = Image.open('solarpic.gif') img1 = photo_image.resize((600, 200)) photo_image = ImageTk.PhotoImage(img1) piclabel = Label(picframe, image=photo_image) piclabel.place(x=10,y=10) piclabel.pack() root.mainloop()
已尝试的参数
我试过以下几种--add-data参数,但问题未解决:
--add-data "solarpic.gif;." --add-data "solarpic.gif;.gif" --add-data "solarpic.gif;solarpic.gif"
解决方案
单文件打包时,PyInstaller会把资源解压到临时目录而非程序运行的当前目录,直接用相对路径无法找到文件。需修改代码获取资源实际路径:
- 修改代码,添加资源路径获取逻辑:
from tkinter import * from PIL import ImageTk, Image import sys import os def get_resource_path(relative_path): # 判断是否为打包后的运行环境 if hasattr(sys, '_MEIPASS'): return os.path.join(sys._MEIPASS, relative_path) # 未打包时的本地路径 return os.path.join(os.path.abspath("."), relative_path) root=Tk() picframe = LabelFrame(root) picframe.grid(column=0, row=0, padx=10, pady=10,sticky=NSEW) # 使用自定义函数获取图片路径 photo_image = Image.open(get_resource_path('solarpic.gif')) img1 = photo_image.resize((600, 200)) photo_image = ImageTk.PhotoImage(img1) piclabel = Label(picframe, image=photo_image) piclabel.place(x=10,y=10) piclabel.pack() root.mainloop()
- 重新执行原打包命令:
pyinstaller --onefile --windowed --add-data "solarpic.gif;." scratch.py
说明:sys._MEIPASS是PyInstaller单文件打包时生成的临时目录路径,程序运行时所有添加的资源都会被解压到该目录。通过判断该属性,可在打包后和本地调试时都正确定位资源文件。
内容的提问来源于stack exchange,提问作者MikeNH
相关产品推荐
相关产品推荐

