gpt4 book ai didi

python - Pyinstaller 在 --onefile --windowed 应用程序中嵌入图像文件夹

转载 作者:太空宇宙 更新时间:2023-11-04 11:11:09 27 4
gpt4 key购买 nike

我正在尝试将包含图像的文件夹嵌入到生成的(使用 PyInstaller)可执行文件中。但这对我不起作用。即使只有一张简单的图片!

我的 main.spec 文件中的 datas 变量如下所示:

datas=[ ('C:\\Users\\<user>\\dir1\\dir2\\MyApp\\images\\*.png', 'images') ],

根据文档:

The first string specifies the file or files as they are in this system now. The second specifies the name of the folder to contain the files at run-time.

在 python 文件中,我读取了这样的图像:

self.SetIcon(wx.Icon("images\\myicon.png"))

最后,这是我使用 PyInstaller 将所有内容打包到 *.exe 中的方式:

pyinstaller --onefile --windowed --icon=images\main32x32.ico main.spec

我收到以下错误:

Failed to load image from file "images\myicon.png"

有人可以告诉我我做错了什么吗?

最佳答案

当你想把一个文件嵌入到你的可执行文件中时,你需要做两个步骤:

首先,添加 add-data 到您的可执行文件(就像您已经做的那样)。其次,在运行时从提取的路径加载文件。

您正在尝试从 images/myicon.png 加载文件,并且路径在您的可执行文件旁边。尽管如此,该文件不存在,同时,运行时文件将被提取到一个临时目录中,例如C:/Users/<user>/AppData/Local/Temp/_MEIXXX .所以它需要从那个目录加载。

您可以使用 sys._MEIPASS 获取提取文件所在的临时路径。此外,您可以创建一个函数来加载外部文件:

import os
import sys


def resource_path(relative_path):
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.abspath("."), relative_path)


self.SetIcon(wx.Icon(resource_path("images/myicon.png")))

关于python - Pyinstaller 在 --onefile --windowed 应用程序中嵌入图像文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58184903/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com