PyInstaller打包exe时无法添加图片文件的问题求助
解决PyInstaller打包pystray脚本找不到图标文件的问题
问题根源
使用--onefile模式打包时,PyInstaller会将所有资源文件打包进exe,运行时自动解压到系统临时目录(由sys._MEIPASS变量指向)。但原代码中直接使用相对路径"gs-image.png",程序会在当前工作目录(exe所在文件夹)查找文件,而非临时解压目录,导致找不到图片。
解决方案
1. 修改Python代码,适配打包后的资源路径
添加资源路径获取逻辑,兼容开发环境和打包后的运行环境:
import webbrowser import pystray import PIL.Image import sys import os # 获取资源文件的绝对路径 def get_resource_path(relative_path): try: # 打包后的临时目录路径 base_path = sys._MEIPASS except Exception: # 开发环境下的当前目录 base_path = os.path.abspath(".") return os.path.join(base_path, relative_path) # 使用新路径加载图片 image = PIL.Image.open(get_resource_path("gs-image.png")) def on_clicked(icon, item): if str(item) == "Open GS Digi Ecosystem": webbrowser.open_new("https://www.google.com/") elif str(item) == "Close": icon.stop() icon = pystray.Icon("test", image, menu=pystray.Menu( pystray.MenuItem("Open GS Digi Ecosystem", on_clicked), pystray.MenuItem("Close", on_clicked) )) icon.run()
2. 确保.spec文件正确配置资源打包
修改.spec文件的datas参数,保证图片被打包进exe:
block_cipher = None a = Analysis( ['webtest.py'], pathex=[], binaries=[], # 配置资源:(源文件路径, 打包后的目标目录),这里设为'.'表示和脚本同层级 datas=[('gs-image.png', '.')], hiddenimports=[], hookspath=[], hooksconfig={}, runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False, ) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE( pyz, a.scripts, a.binaries, a.zipfiles, a.datas, [], name='webtest', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, upx_exclude=[], runtime_tmpdir=None, console=False, disable_windowed_traceback=False, argv_emulation=False, target_arch=None, codesign_identity=None, entitlements_file=None, icon=['gs-icon.ico'], )
3. 重新打包
执行以下命令完成打包:
pyinstaller webtest.spec
打包后的exe可在任意位置独立运行,无需手动复制图片到exe目录。
内容的提问来源于stack exchange,提问作者batesburgers
相关产品推荐
相关产品推荐

