Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
579 views
in Technique[技术] by (71.8m points)

python - Pyinstaller and --onefile: How to include an image in the exe file

I have created an exe file using Pyinstaller.

pyinstaller.exe --onefile --icon='Loco.ico program.py

In the program, I include an image in my plots, and when I run the program alone in its folder, I get the following:

IOError: [Errno 2] No such file or directory: 'Logo.png'

One solution is to include the image in the folder of the exe as seen in the link below:

pyinstaller does not show images and icon

But then again the whole point of --onefile is to have exactly that, not need the image in addition. I think the solution may be in this link, but I haven't understood it.

Bundling data files with PyInstaller (--onefile)

my spec file looks the following:

# -*- mode: python -*-
a = Analysis(['AMOS_Visualizer.py'],
    pathex=['C:\Users\elu\PycharmProjects\Prosjektet\Forsok splitting'],
    hiddenimports=[],
    hookspath=None,
    runtime_hooks=None)

pyz = PYZ(a.pure)
exe = EXE(pyz,
      a.scripts,
      a.binaries,
      a.zipfiles,
      a.datas,
      name='AMOS_Visualizer.exe',
      debug=False,
      strip=None,
      upx=True,
      console=True , icon='AMOS.ico')
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Edit:

I belive I found the solution to my problem.

# -*- mode: python -*-
a = Analysis(['AMOS_Visualizer.py'],
         pathex=['C:\Users\elu\PycharmProjects\Prosjektet\Forsok splitting'],
         hiddenimports=[],
         hookspath=None,
         runtime_hooks=None)

for d in a.datas:
    if 'pyconfig' in d[0]:
        a.datas.remove(d)
        break

a.datas += [('Logo.png','C:\Users\elu\PycharmProjects\Prosjektet\Forsok splitting\Logo.png', 'Data')]
pyz = PYZ(a.pure)
exe = EXE(pyz,
      a.scripts,
      a.binaries,
      a.zipfiles,
      a.datas,
      name='AMOS_Visualizer.exe',
      debug=False,
      strip=None,
      upx=True,
      console=True, icon='C:\Users\elu\PycharmProjects\Prosjektet\Forsok splitting\AMOS.ico')

And adding the following to my main.py script

def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

Logo = resource_path("Logo.png")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...