Search code examples
pythonpyinstallerpystray

correct path for files with PIL after compiling with pyinstaller


I'm using auto-py-to-exe which is based on pyinstaller, trying to make an executable with --onefile, using pystray to make a tray app, but after compiling I get an error that the icon file cannot be found. See that in the code I tried to use os.path to get the most specific path possible, even so it is not possible to find.

The question is, how to make this path correct using --onfile?


import pystray
from PIL import Image
# ==============================
from os.path import join
from os import getcwd


TilleTables = SetInterval(1, TileTables)
# print(join(getcwd(), 'icon.png'))
menuImg = Image.open(join(getcwd(), 'icon.png'))

MenuIcon = pystray.Icon('Neural', menuImg, menu=pystray.Menu(
    pystray.MenuItem('Exit', HandleTrayClick),

))

MenuIcon.run()
Traceback (most recent call last):
  File "main.py", line 20, in <module>
  File "PIL\Image.py", line 3092, in open
FileNotFoundError: [Errno 2] No such file or directory: 'icon.png'

Auto-py-to-exe image

Error Screenshot


Solution

  • For future readers, the path of pyinstaller must be relative after the build, so it is necessary to add the function that creates a temporary file for the icon... Bundling data files with PyInstaller (--onefile)

    the solution found was to add the patch to this function and within the auto-py-to-exe set the icon file to the additional files

    menuImg = Image.open(resource_path('icon.png'))
    
    MenuIcon = pystray.Icon('Neural', menuImg, menu=pystray.Menu(
        pystray.MenuItem('Exit', HandleTrayClick),
    
    ))
    
    MenuIcon.run()
    

    So the icon appears in the temp folder and can be found by the program.