Pyinstaller 和 --onefile:如何在 exe 文件中包含图像 [英] Pyinstaller and --onefile: How to include an image in the exe file
问题描述
我使用 Pyinstaller 创建了一个 exe 文件.
I have created an exe file using Pyinstaller.
pyinstaller.exe --onefile --icon='Loco.ico program.py
在程序中,我在绘图中包含了一个图像,当我在其文件夹中单独运行该程序时,我得到以下信息:
In the program, I include an image in my plots, and when I run the program alone in its folder, I get the following:
IOError: [Errno 2] No such file or directory: 'Logo.png'
一种解决方案是将图像包含在 exe 文件夹中,如下面的链接所示:
One solution is to include the image in the folder of the exe as seen in the link below:
但话说回来,--onefile 的全部意义在于拥有它,而不需要额外的图像.我认为解决方案可能在此链接中,但我还没有理解.
But then again the whole point of --onefile is to have exactly that, not need the image in addition. I think the solution may be in this link, but I haven't understood it.
使用 PyInstaller (--onefile) 捆绑数据文件
我的规范文件如下所示:
my spec file looks the following:
# -*- mode: python -*-
a = Analysis(['AMOS_Visualizer.py'],
pathex=['C:\\Users\\elu\\PycharmProjects\\Prosjektet\\Forsok splitting'],
hiddenimports=[],
hookspath=None,
runtime_hooks=None)
pyz = PYZ(a.pure)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
name='AMOS_Visualizer.exe',
debug=False,
strip=None,
upx=True,
console=True , icon='AMOS.ico')
推荐答案
我相信我找到了解决问题的方法.
I belive I found the solution to my problem.
# -*- mode: python -*-
a = Analysis(['AMOS_Visualizer.py'],
pathex=['C:\\Users\\elu\\PycharmProjects\\Prosjektet\\Forsok splitting'],
hiddenimports=[],
hookspath=None,
runtime_hooks=None)
for d in a.datas:
if 'pyconfig' in d[0]:
a.datas.remove(d)
break
a.datas += [('Logo.png','C:\\Users\\elu\\PycharmProjects\\Prosjektet\\Forsok splitting\\Logo.png', 'Data')]
pyz = PYZ(a.pure)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
name='AMOS_Visualizer.exe',
debug=False,
strip=None,
upx=True,
console=True, icon='C:\\Users\\elu\\PycharmProjects\\Prosjektet\\Forsok splitting\\AMOS.ico')
并将以下内容添加到我的 main.py 脚本中
And adding the following to my main.py script
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
Logo = resource_path("Logo.png")
这篇关于Pyinstaller 和 --onefile:如何在 exe 文件中包含图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!