如何使用 pyinstaller 包含文件? [英] How do I include files with pyinstaller?
问题描述
我也使用 tkinter 用 python 3.7 制作了一个程序.由于我使用的是外部图片,因此在将所有内容编译为一个 exe 时需要包含它们.我试过做 --add-data "bg.png;files"
但我仍然收到这个错误:
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: 无法打开 "files/bg.png": 没有这样的文件或目录
_tkinter.TclError: couldn't open "files/bg.png": no such file or directory
代码如下:
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')
我做错了什么?我也尝试过 --add-binary
,将文件添加到我的规范文件中.实在想不通!
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!
推荐答案
抱歉,我以为只有 -F/--one-file 会产生这种行为,但看起来任何与 pyinstaller 的捆绑都需要这样的更改.
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")
然后像这样将它与 pyinstaller 捆绑在一起:
And then bundle it with pyinstaller like this:
pyinstaller --clean -y -n "output_name" --add-data="filesg.png;files" script.py
这篇关于如何使用 pyinstaller 包含文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!