Search code examples
pythonpython-3.xtkinterpyinstaller

Image won't load for tkinter program compiled with pyinstaller


I have a tkinter program that includes a .png image. I have compiled it using pyinstaller and the --onefile option so I have to access the image in a temporary location. This is the code I am using:

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

    return os.path.join(base_path, relative_path)
title = PhotoImage(file=resource_path("xgol.png"))

Here is my .spec file:

# -*- mode: python -*-

block_cipher = None


a = Analysis(['XGols.py'],
             pathex=['C:\\Users\\Sam\\OneDrive\\Computing\\Python Projects\\FootballPredict'],
             binaries=[],
             datas=[('Ball.ico', 'Ball.ico'), ('xgol.png', 'xgol.png')],
             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='XGols',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          runtime_tmpdir=None,
          console=True , icon='Ball.ico')

To compile the program I use:

pyinstaller --onefile XGols.spec

This is the error that I get when I run the executable

_tkinter.TclError: couldn't open "C:\Users\Sam\AppData\Local\Temp\_MEI61842\xgol.png": permission denied

I have tried running as administrator.


Solution

  • In your .spec file, additional data files should be listed like so:

    datas=[('Ball.ico', '.'), ('xgol.png', '.')]
    

    From the documentation:

    Each tuple has two values, both of which must be strings:

    • 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.