pythonimagetkinter

Why is Python's Tkinter Image function unable to locate the PNG file?


Traceback (most recent call last):
  File "c:\Users\####\Desktop\Python_Demo_Projects\Quiz_Program\problematic.py", line 51, in <module>
    previous_slide()
  File "c:\Users\####\Desktop\Python_Demo_Projects\Quiz_Program\problematic.py", line 43, in previous_slide
    temp_graphic = Image(resource_path(graphic))
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\Lib\tkinter\__init__.py", line 4097, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: image type "c:\Users\####\Desktop\Python_Demo_Projects\Quiz_Program\assets\q1g.png" doesn't exist
from tkinter import *
from tkinter import filedialog
import os
import sys

temp_table = [("a","Answer is a because A","assets\q1g.png"),
              ("c","C is the answer","assets\q2g.png"),
              ("d","D is the answer","assets\q3g.png")]

current_placard = 0

def resource_path(relative_path):
    """ Get the absolute path to a resource, works for dev and for PyInstaller """
    try:
        # If running as a bundled exe, sys._MEIPASS will be the temp folder where the files are extracted
        base_path = sys._MEIPASS
    except AttributeError:
        # If running as a script, use the current directory
        base_path = os.path.dirname(os.path.abspath(__file__))
    
    return os.path.join(base_path, relative_path)

def load_quiz_file():
    global temp_table
    try:
        filepath = filedialog.askopenfilename(title="Open File",filetypes= (("text file","*.txt"),
                                            ("all files","*.*")))
        file = open(filepath,"r")
        temp_table = Variable(file.read())
        file.close()

        window.update_idletasks()
        #text_ans.insert("1.0","Quiz loaded Successfully")
           
    except Exception as e:
        print(f"Error reading from file: {e}")

def previous_slide():
    global current_placard
    if current_placard > 0:
        current_placard -= 1
    answer,explain,graphic = temp_table[current_placard]
    temp_graphic = Image(resource_path(graphic))
    label_q.config(image=temp_graphic)

window = Tk()

label_q = Label(window, height=23, background="red",text="Question placard will be displayed here.")
label_q.pack(fill=X,expand=True)

previous_slide()
window.mainloop()

The file is in the correct place, and even Tkinter shows the traceback going to the right place and file, but it doesn't see it. I assume this is me, but I can't for the life of me figure out why.

I have tried confirming the file path (correct), remaking the Image object (no change), printing the image path (same as is states not being there).

I have had this issue in the past, but not to this degree, as if the image doesn't exist. Previously it was a simple typo, or a restart of VSC to fix. This time none of that has worked.


Solution

  • The error correctly explains what is happening

    _tkinter.TclError: image type "c:\Users\####\Desktop\Python_Demo_Projects\Quiz_Program\assets\q1g.png" doesn't exist
    

    you are passing it a path to an image when it is expecting a image type.

    if you want to load an image from a file you can use PhotoImage like this

    temp_graphic = PhotoImage(file=resource_path(graphic))