pythontkinterpackageexesoftware-distribution

How to convert tkinter script which uses multiple image resources to .exe | image no such file or directory


I am trying to create an executable of my script, but running the .exe does not find the image. I have tried both onefile and multiples and pasting the images inside but it does not work.

These would be my images.

root = Tk()
root.title("Tai Project")
root.geometry("600x600")
root.resizable(0, 0)
img = PhotoImage(file="Tai_Project\ccc.png")
img_opo = PhotoImage(file="Tai_Project\opo.png")
img_label = PhotoImage(file="Tai_Project\labeltest.png")

Solution

  • You can use this function for all paths:

    import sys
    import os
    
    
    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)
    

    Usage example:

    img = PhotoImage(file=resource_path("Tai_Project\ccc.png"))
    

    Also in your .spec file you need to match directories in "datas" section like this:

    a.datas += [("Tai_Project\ccc.png","C:\\Users\\username\\projects\\my_project\\Tai_Project\\ccc.png", "DATA")]
    

    This way your files will be included in .exe and will be available in TEMP directory which is created when you run your program.