pyinstaller 在 exe 文件中添加带有图像的文件夹 [英] pyinstaller add folder with images in exe file

查看:56
本文介绍了pyinstaller 在 exe 文件中添加带有图像的文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 main.py 的 python 脚本,它使用相同路径中的一些图像,在图像文件夹中.

I have a python script called main.py that uses some images in the same path, in images folder.

我想创建一个 exe 文件,其中还包含 main.py 脚本中使用的图像.

I want to create one exe file that has also the images that are used from main.py script.

myprogram 
|-images_folder 
|-main.py

我该怎么办?

我正在启动:

pyinstaller --onefile --windowed main.py

但是它生成了一个无法可视化图像的 main.exe,因为它们不包含在 exe 中.

But it generates a main.exe that can't visualize the images, because they are not included in exe.

推荐答案

要在 .exe 文件中包含图像,您需要在 .spec 文件中指定它们:

To include the images in your .exe file, you need to specify them in a .spec file:

# -*- mode: python -*-

block_cipher = None


a = Analysis(['main.py'],
             pathex=['C:\\Python36\\Scripts'],
             binaries=[],
             datas=[],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)

a.datas += [('image.png','path_to_image', "DATA")]

pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)

exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name='Name of your program',
          debug=False,
          strip=False,
          upx=True,
          console=False)

将其另存为 main.spec 并使用 pyinstaller main.spec 运行它不要忘记将image.png"替换为您的实际图像文件,并将path_to_image"替换为您的图像的文件路径.另外,设置 pathex= 任何你的main.py"文件所在的目录.

Save it as main.spec and run it with pyinstaller main.spec Don't forget to replace "image.png" with your actual image file and "path_to_image" with the file path to your image. Also, set pathex= whatever directory your "main.py" file is in.

这将确保图像存储在可执行文件中.要访问它们,请将此功能添加到您的 main.py 文件中:

This will ensure the images are stored within the executable file. To access them, add this fucntion to your main.py file:

import os

def resource_path(relative_path):
    try:
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

然后,每次使用文件名image.png"时,将其替换为resource_path("image.png").

Then, every time you would use the file name "image.png", replace it with resource_path("image.png").

这篇关于pyinstaller 在 exe 文件中添加带有图像的文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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