且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

pyinstaller 在 exe 文件中添加带有图像的文件夹

更新时间:2023-11-22 15:13:28

要在 .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").