如何使用 pyinstaller 包含文件?

How do I include files with pyinstaller?

我也用 python 3.7 使用 tkinter 制作了一个程序。由于我使用的是外部图片,因此在将所有内容编译为一个 exe 时需要包含它们。我试过 --add-data "bg.png;files" 但我仍然收到此错误:

_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,将文件添加到我的规范文件中。真的想不通!

抱歉,我以为只有 -F/--one-file 会出现这样的行为,但看起来任何与 pyinstaller 的捆绑都需要这样的更改。

您需要像这样更改您的代码,如 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 捆绑在一起:

pyinstaller --clean -y -n "output_name" --add-data="files\bg.png;files" script.py