如何在pyinstaller中包含文件?

2024-04-25 17:16:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我也用tkinter用python3.7编写了一个程序。因为我使用的是外部图片,所以当我把所有东西编译成一个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,将该文件添加到我的spec文件中。真的搞不懂!在


Tags: 文件image程序adddatapngtkinter图片
1条回答
网友
1楼 · 发布于 2024-04-25 17:16:16

抱歉,我以为只有-F/1个文件会产生这种行为,但是看起来任何与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捆绑在一起,如下所示:

^{pr2}$

相关问题 更多 >