Pyinstaller 在 --onefile --windowed 应用程序中嵌入图像文件夹 [英] Pyinstaller embed images folder in --onefile --windowed application

查看:68
本文介绍了Pyinstaller 在 --onefile --windowed 应用程序中嵌入图像文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to embed a folder with images into generated (with PyInstaller) executable. But it doesn't work for me. Even with one simple image!

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 文件中,我像这样读取图像:

In the python file I read the image like this:

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

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

Finally, this is how I package everything in the *.exe using PyInstaller:

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

我收到以下错误:

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

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

Could someone tell me what I'm doing wrong?

推荐答案

当您想将文件嵌入到可执行文件中时,您需要做两件事:

When you want to embed a file into your executable you need to do two things:

首先,添加add-data 到你的可执行文件(就像你已经做的那样).接下来,在运行时从提取的路径加载文件.

First, add it with add-data to your executable (as you already did). Next, load the file from the extracted path on runtime.

在这里,您正在加载 images\\myicon.png 中的文件,这是可执行文件旁边的路径,但该文件不存在.运行时文件将被提取到临时目录中,例如 C:/Users//AppData/Local/Temp/_MEIXXX 并且需要从该目录加载.

Here you are loading the file in images\\myicon.png which is the path next to your executable but the file is not there. The runtime files would be extracted in a temp directory e.g C:/Users/<user>/AppData/Local/Temp/_MEIXXX and need to be loaded from this directory.

您可以使用sys._MEIPASS 获取解压文件所在的临时路径.您还可以创建一个函数来加载文件:

You can use sys._MEIPASS to get the temp path where the extracted files are located. You can also create a function to load files:

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")))

这篇关于Pyinstaller 在 --onefile --windowed 应用程序中嵌入图像文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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