28

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'

One solution is to include the image in the folder of the exe as seen in the link below:

pyinstaller does not show images and icon

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.

Bundling data files with 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')
1

15 Answers 15

24

A clear and unambiguous guide

Despite the explanations on the Internet, it took me several hours to come up with an independent application that contains several images, does not open a console window while execution and is combined in only one file. Here is my solution that works for Mac OS at least:

Step 1: Change directory

Change to the directory with the file to be made executable:

cd PATH_OF_YOUR_FILE

Make sure the images you need for your program are also in the folder with your Python file you want to make executable.

Step 2: Add code to your Python file

Add the following to the Python file you want to make executable:

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)

Replace the file names with resource_path("FILENAME").

Example:

image1 = Image.open("image.png")

# to:

image1 = Image.open(resource_path("image.png"))

Step 3: Create the executable

Now run the following code (replace the image names and the file name):

pyinstaller --onefile --windowed --add-data "picture1.jpeg:." --add-data "picture2.png:." your_file.py

Note: Any number of images can be added.

Explanations:

--onefile: Creates a one-file bundled executable. Synonyms: -F

--windowed: Ensures that no console is opened during execution. Synonyms: -w and --noconsole

You're done! 🎉

The application is now in the dist directory, which is in the same directory as your Python file.

It should now be possible to drag this to another Mac and run it there once enabled via Settings -> Security & Privacy.

I hope this helped you. Enjoy the result, have a cup of tea and sit back.

8
  • 14
    For windows need to change picture1.jpeg:. to picture1.jpeg;.
    – lu3si
    Sep 28, 2022 at 10:04
  • On Linux I still have the problem that the picture isn't displayed. No error message or anything like that. Maybe you had a similar problem?
    – lu3si
    Sep 28, 2022 at 10:05
  • Hey @lu3si: I haven't tested it for Linux. Unfortunately I can't tell you what caused the problem. Sep 28, 2022 at 12:54
  • Too bad. I had hopped that the commands on Linux are very similar to iOS. I will comment on my solution when I find it.
    – lu3si
    Sep 29, 2022 at 7:17
  • My problem was caused by using ImageTk.PhotoImage
    – lu3si
    Sep 29, 2022 at 9:37
22

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

Struggled with this. Key thing to know is that, for --onefile builds, your images get stored in the sys._MEIPASS folder.

This line of code in my tkinter app was breaking my .exe:

self.wm_iconbitmap("favicon.ico")

To fix it, I replaced it with this:

self.wm_iconbitmap(get_path("favicon.ico"))

Where get_path() was a little function that I added to the module:

def get_path(filename):
    if hasattr(sys, "_MEIPASS"):
        return os.path.join(sys._MEIPASS, filename)
    else:
        return filename

For context, I ran this command in CLI to build the .exe:

pyinstaller --noconfirm --onefile --windowed --add-data "C:/Users/[...]/favicon.ico;."  "C:/Users/[...]/main.py"

Note, ran this on Win10.

Got here thanks to lots of other Stack Overflow contributors.

1
  • 3
    This is the right answer. The one currently accepted did not work for me.
    – Ethicist
    Dec 5, 2021 at 20:47
7

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.

0
5

This is a variation of the following: Bundling data files with PyInstaller (--onefile), and the given answer is clearer.

In 2 lines:

  1. You have to add your image files in "datas" (either in your spec files or with a PyInstaller hook script)
  2. Use the sys._MEIPASS if it exists,
    using the single line base_path = getattr(sys, '_MEIPASS', '.')+'/' to get a "root_path" variable to concatenation to all your files' paths.
    Then, filepath = base_path + filepath
1
  • If you think it's a duplicate, just flag it as such. No need to rewrite the answer here.
    – Praveen
    Dec 7, 2016 at 19:21
3

Add "datas = ['Location of your file']," before "hiddenimports = []". It will do. In my case this worked

    # -*- mode: python -*-

block_cipher = None


a = Analysis(['embed.py'],
             pathex=['C:\\Users\\Aravind\\Desktop\\exe'],
             binaries=[],
             datas=['C:\\Users\\Aravind\\Desktop\\exe\\dist\\map.png'],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name='embed',
          debug=False,
          strip=False,
          upx=True,
          runtime_tmpdir=None,
          console=True )
1
  • 4
    I think you need to use a tuple datas=[('C:\\Users\\Aravind\\Desktop\\exe\\dist\\map.png','.')], and you also need to use pyi -makespec --onefile file.py first, edit the .spec file to include the above and then build pysintaller --options myfile.spec
    – mobcdi
    Jan 28, 2019 at 21:33
3

Finally it's simpler than what I found on various web pages & here.

1) You specify in your code the relative path in temporary directory when the code is run as a compiled executable:

if getattr(sys, 'frozen', False): # Running as compiled
    running_dir = sys._MEIPASS + "/files/" # Same path name than pyinstaller option
else:
    running_dir = "./" # Path name when run with Python interpreter
iconFileName = running_dir + "mylogo.ico"
if os.path.isfile(iconFileName):
    root.iconbitmap(iconFileName) # Exemple for tkinter usage

2) You give the path in the temporary directory created where your files will be stored on the compiler option:

pyinstaller --onefile --add-binary "mylogo.ico;files" -i mylogo.ico myMainPrg.py

This way, you don't have to know the complete path where your files are in development and where you are going to install them in production.

2

I have tried a lot but this worked after an hour:

When I run my programfile MilaBild.py the first time with:

pyinstaller -F -w MilaBild.py

it seams to create the ".spec" file that I need to add the following to as stated in other coments above:

a.datas += [('rosa.png','C:\\Python34\\rosa.png', 'DATA')]

the name of my imagefile is rosa.png. It is lokated at the same directory as my programfile MilaBild.py.

I then allso had to add the part above as mentioned in coment above in my actuall program file:

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)

Then I added in the part that gets the file to a variable and it worked:

rosa = resource_path("rosa.png")

I tryed a lot and only to make this work took me one hour. Later I will try to make it with two images, sounds and subdirectories. But for now it it is 23:45 a'clock and that will be Another day, I feel very happy with this soo far, great break trough for me.

1

Sadly, the top answers did not work for me. How I got it working on Windows/PySide6 with a UI generated by Qt Creator:

  1. Place the image (in my case, reload_icon.png) in the same folder as main.py. I could not get it working if the image was placed in a different folder, e.g. images/reload_icon.png.

  2. Create a resource file images.qrc (I used the prefix "images" in mine)

    <RCC>
        <qresource prefix="/images">
            <file>reload_icon.png</file>
        </qresource>
    </RCC>
    
  3. Convert images.qrc into images.py

    pyside6-rcc.exe images.qrc -o images.py
    
  4. In main.py, import images.py and setIcon() on the required object

    import images
    # ...
    self.ui.my_button.setIcon(QIcon(":/images/reload_icon.png"))
    

note how the path starts with :/images, which indicates we are using a resource file with the images prefix.

  1. Build the executable, specify that we want images.py bundled into the .exe file
    pyinstaller.exe --onefile --windowed --add-data=images.py:. main.py
    
0

When I was trying to do a testing with a small app, I then saw in my program script, I was using the images directory which is in my C: drive to reference the images, i.e for example:

      xxx.setStyleSheet("background-image: url(C:\pictures\image1.jpg);"

whereas I was supposed to ensure the images are in the same folder with the project file which is in my F: drive

So when I copied the images to the same folder housing the project file in my F: drive, I just used:

   xxx.setStyleSheet("background-image: url(image1.jpg;")

It worked fine after I changed it to this format

I only copied the images to the project folder without using that path in my code reference but used the C: directory to reference it in my code before. That's the reason it didn't work as expected.

So with the right path in my script, I used this command :

     pyinstaller --windowed  --add-data "image1.jpg;." --add-data "image2.jpg;." --add-data "image3.jpg;." --icon=myLogo.ico myPythonFile.py

and all the avatars and background images I used in my program showed in the areas they're meant to be in the application and also could be seen in other computers the app was deployed to.

Admins please permit this. I decided to drop it down because I or someone else me might need it tomorrow. The other answers I saw were somehow confusing and difficult to me

0

Converting the image to base64 code

First convert your image to a base64 code using the same name library in a separate code and save the result in another python file so that you can import it in your main python file. This is necessary or else you will receive file not found error after converting .py to .exe with pyinstaller and moving the exe file if the image is missing in the new location.

import base64
pic = open('file.png', 'rb')
content = f'img = {base64.b64encode(pic.read())}\n'
pic.close()

with open('pic2str.py', 'w') as f:
    f.write(content) 

Importing the base64 code in your main python file

Now import the variable in your main file so that there is no use of your image file address in your main code.

from pic2str import img

bg = base64.b64decode(img)
image = tk.PhotoImage(data=bg)
label = tk.Label(
    root,
    compound="center",
    text="Your Text",
    font=("Your Font", Your Font size),
    fg="Your Color",
    image=image)
label.pack(fill="both", expand=1)

Now you can use your converted to .exe file independently from the image you used.

0

According to the docs, you can use __file__ to work out the path to the script if not bundled or the path to the bundle folder when it's bundled.

For my situation, I wanted to include an Excel file and a geckodriver, so I created this function:

import os

def resource_path(file):
    data_dir = os.path.abspath(os.path.dirname(__file__))
    return os.path.join(data_dir, file)

and I call it in the script like:

DRIVER_PATH = resource_path('geckodriver')

This works when I run with python and when I bundle it using --onefile

here's how I build it:

pyinstaller --onefile --add-data "geckodriver:." --add-data "Myfile-decrypted.xlsx:." main.py 
0
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
if getattr(sys, 'frozen', False):
    # Running as bundled executable
    base_path = os.path.dirname(sys.executable)
else:
    # Running in development
    base_path = os.path.abspath(os.path.dirname(__file__))

return os.path.join(base_path, relative_path)

Use this function instead of try and error method.

If you have made the assets folder which contains images, fonts, icons etc then need to copy the folder inside the dist folder in order to work.

Atleast it worked in my mac os.

-1

Add an -i argument and an appropriate path:

pyinstaller --onefile -i icon.ico .\app.py
-3

Nothings Worries. I've the same problem and got an answer by just doing this... Copy all my Images and paste them in dist/ and build/ directory created by pyinstaller, and problem solved. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.