I have a python script called main.py that uses some images in the same path, in images folder.
I want to create one exe file that has also the images that are used from main.py script.
myprogram
|-images_folder
|-main.py
How I have to do?
I am launching:
pyinstaller --onefile --windowed main.py
But it generates a main.exe that can't visualize the images, because they are not included in exe.
To include the images in your .exe file, you need to specify them in a .spec file:
# -*- mode: python -*-
block_cipher = None
a = Analysis(['main.py'],
pathex=['C:\\Python36\\Scripts'],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher)
a.datas += [('image.png','path_to_image', "DATA")]
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
name='Name of your program',
debug=False,
strip=False,
upx=True,
console=False)
Save it as main.spec and run it with pyinstaller main.spec
Don't forget to replace "image.png" with your actual image file and "path_to_image" with the file path to your image. Also, set pathex=
whatever directory your "main.py" file is in.
This will ensure the images are stored within the executable file. To access them, add this fucntion to your main.py file:
import os
def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
Then, every time you would use the file name "image.png", replace it with resource_path("image.png")
.
Just to improve the last answer by Francisco Rodrigues.
a.datas += [('image.png','path_to_image', "DATA")]
The 'path_to_image' more likely means the image path with "image.png" behind.
Like this:
a.datas += [('image.png','C:\\User\\user\\Desktop\\image.png', "DATA")]
Instead of :
a.datas += [('image.png','C:\\User\\user\\Desktop', "DATA")]
or there's an error saying "cannot find " the file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With