How to include images in one file with python pyinstaller

流过昼夜 提交于 2019-12-24 18:48:51

问题


I have image locations included in my python code but when I compile to an exe with pyinstaller using one file and all of the --add-data commands, the exe wont run stating that the image can not be found.

This is my spec file

# -*- mode: python -*-

block_cipher = None


a = Analysis(['datasorter.py'],
             pathex=["C:\\Users\\Rat's Nest\\Desktop\\DATASORTERS\\V1.1"],
             binaries=[],
             datas=[('clogo.png', '.'), ('FullLogo.png', '.'), 
             ('logo.ico','.')],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          [],
          name='datasorter',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          runtime_tmpdir=None,
          console=False , icon='logo.ico')

回答1:


First, there is no need to add your executable icon as a data, putting it in icon param would be enough.

Next, when you add a data to PyInstaller it would bring your data and extract it in temp folder (e.g. C:\Users\Rat's Nest\Appdata\local\temp\_MEIXXXX\) so you need to change your code to open your files from that directory. A good practice is to use this function in your code to retrieve your data. When running executable sys._MEIPASS would be equal to the PyInstaller temp folder.

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)

Then you can use it with something like new_source = resource_path("clogo.png").



来源:https://stackoverflow.com/questions/56204425/how-to-include-images-in-one-file-with-python-pyinstaller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!