如何在pyinstaller中包含文件? [英] How do I include files with pyinstaller?

查看:354
本文介绍了如何在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 ,将文件添加到我的spec文件中。

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 /-一个文件才能产生这种行为,但是看起来任何与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="files\bg.png;files" script.py

这篇关于如何在pyinstaller中包含文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆