Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I include files with pyinstaller?

I have made a program with python 3.7 using tkinter aswell. Since I am using external pictures I need to include them when I compile everything to one exe. I have tried doing --add-data "bg.png;files" but I still get this error:

_tkinter.TclError: couldn't open "files/bg.png": no such file or directory

Here is the code:

image = PhotoImage(file="files/bg.png")
w = image.width()
h = image.height()
x = 316
y = 246
mainGui.geometry("%dx%d+%d+%d" % (w, h, x, y))
panel = Label(mainGui, image=image)
panel.pack(side='top', fill='both', expand='yes')

What am I doing wrong? I have tried --add-binary as well, adding the file to my spec file. Seriously can't figure this out!

like image 940
Michael L Avatar asked Dec 03 '18 04:12

Michael L


People also ask

Does PyInstaller include imports?

Analysis: Finding the Files Your Program Needs To find out, PyInstaller finds all the import statements in your script. It finds the imported modules and looks in them for import statements, and so on recursively, until it has a complete list of modules your script may use.

Does PyInstaller include libraries?

spec extension. The . Spec file has the same name as the python script file. PyInstaller creates a distribution directory, DIST containing the main executable and the dynamic libraries bundled in an executable file.


1 Answers

Sorry, I thought that only -F/--one-file makes such behavior, but looks like any bundling with pyinstaller needs such changes.

You need to change your code like this, as explained in this answer:

import sys

if getattr(sys, 'frozen', False):
    image = PhotoImage(file=os.path.join(sys._MEIPASS, "files/bg.png"))
else:
    image = PhotoImage(file="files/bg.png")

And then bundle it with pyinstaller like this:

pyinstaller --clean -y -n "output_name" --add-data="files\bg.png;files" script.py
like image 60
Kamal Avatar answered Sep 27 '22 16:09

Kamal