以下是我使用的代码,它完美地运行了。
import sys
from os.path import join, abspath
def resource_path(relative_path):
if hasattr(sys, '_MEIPASS'):
return join(sys._MEIPASS, relative_path)
return join(abspath("."), relative_path)
请在
spec
文件中添加以下代码:
a.datas += [ ('back.png', 'icon/back.png', 'DATA')]
其中'back.png'
是我的图像路径,将保存在pyinstaller exe包中,而'icon/back.png'
是我在打包之前将图像文件放置在icon
文件夹中的路径。
block_cipher = None
a = Analysis(['main.py'],
pathex=['C:\\Users\\User\\Documents\\GitHub\\Mypath'],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=['mkl','whl'],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False)
a.datas += [ ('back.png', 'icon/back.png', 'DATA')]
a.datas += [ ('main.ico', 'icon/main.ico', 'DATA')]
a.datas += [ ('folder.png', 'icon/folder.png', 'DATA')]
a.datas += [ ('download.png', 'icon/download.png', 'DATA')]
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
[],
name='main',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
upx_exclude=[],
runtime_tmpdir=None,
console=True , icon='icon\\main.ico')
然后你可以像这样调用你的图片:resource_path('download.png')