Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pyinstaller add folder with images in exe file

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.

like image 649
michele Avatar asked Jul 10 '18 11:07

michele


2 Answers

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").

like image 198
ArmindoFlores Avatar answered Sep 19 '22 22:09

ArmindoFlores


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.

like image 21
Book Sun Avatar answered Sep 16 '22 22:09

Book Sun