Pyinstaller and --onefile: How to include an image in the exe file
This is a variation of the following: Bundling data files with PyInstaller (--onefile), and the given answer is clearer.
In 2 lines:
- You have to add your image files in "datas" (either in your spec files or with a PyInstaller hook script)
- Use the sys._MEIPASS if it
exists,
using the single linebase_path = getattr(sys, '_MEIPASS', '.')+'/'
to get a "root_path" variable to concatenation to all your files' paths.
Then,filepath = base_path + filepath
Edit:
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')
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")
If you are using Qt Designer you can do it by creating an resource file and adding all images you want, including the Logo.png, to this resource.
To create a resource file you can follow the steps in Inserting an image in GUI using QT Designer .
After you have inserted the images in the resource file, assign the Logo.png to the Window icon, save the QtDesigner interface and convert the resource file using the command: pyrcc4 -py3 resourcetest.qrc -o resourcetest_rc.py
Finally, use --onefile option to create the exe file. No need to edit the spec file.