How do I include files with pyinstaller?
10,434
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
Author by
Michael L
Updated on June 24, 2022Comments
-
Michael L almost 2 years
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! -
Michael L over 5 yearsYou are a legend, thank you soooo much! Works flawless!
-
Michael L over 5 yearsJust a small update. I have some sound aswell and I tried adapting those lines into my winsound.Playsound, but it doesn't seem to take it the same way as tkinter does. winsound.PlaySound(os.path.join(sys._MEIPASS, "files/bgm.wav", winsound.SND_LOOP + winsound.SND_ASYNC)) Do you know how to formulate it so python understand it? @Kamal Don't really understand how I can use the 'code' function here on stackoverflow, so it hope its possible to read it.
-
Kamal over 5 yearsYou have closed the parenthesis of
os.path.join
at wrong position, try:winsound.PlaySound(os.path.join(sys._MEIPASS, "files/bgm.wav"), winsound.SND_LOOP+winsound.SND_ASYNC)
. And check here for formatting help. -
Michael L over 5 yearsThat did it, thanks for all the help @Kamal! I started programming a week ago, feels good to learn new stuff all the time!