[Python] Why do I get an error when trying to create a canvas image with tkinter even though I...

Discussão em 'Python' iniciado por Stack, Fevereiro 9, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to create an image for my tkinter canvas. The image path is fine, the PhotoImage object gets created without issue but when I try to create the canvas image using the PhotoImage object, an exception is raised. I have the PhotoImage() stored as an attribute of the class. I have also tried saving the image to a global list to prevent garbage collection, but neither work.

    If I run this test code, everything works fine and the canvas image is created:

    import tkinter as tk
    from tkinter import PhotoImage

    root = tk.Tk()
    canvas = tk.Canvas(root, width=800, height=600)
    canvas.pack()

    image_path = "images/card_front2.png"
    try:
    pic = PhotoImage(file=image_path)
    canvas.create_image(415, 265, image=pic)
    except Exception as e:
    print(f"Error loading image: {e}")

    root.mainloop()


    But now I am creating tkinter class objects within my own classes to create a flashcard app. Here is the relevant portion of my class to create the canvas setup that will be rooted to the reference_window. The focus is on the final 4 lines.

    class CanvasSetup:
    dutch_word = ""
    eng_word = ""
    counter = 1

    def __init__(self, window_ref, data, lang, colour_light, colour_dark, colour_neutral):
    ##### Define inputs #####
    self.window_ref = window_ref
    self.data = data
    self.my_lang = lang
    self.colour_light = colour_light
    self.colour_dark = colour_dark
    self.colour_neutral = colour_neutral

    ##### Get image for English canvas #####
    self.eng_pic = PhotoImage(file="card_back2.png")
    self.non_eng_pic = None # Initially set to None


    ##### Get number list for length of data inputted #####
    self.number_list = [num for num in range(len(self.data["ENG"].keys()))]

    ##### Create canvas #####
    ## Get image for other lang canvas ##
    if self.my_lang == "Dutch":
    self.non_eng_pic = PhotoImage(file="card_front2.png")
    else:
    self.non_eng_pic = PhotoImage(file="card_front2.png")
    self.canvas = Canvas(self.window_ref, width=800, height=500, highlightthickness=0, bg=self.colour_light)
    self.canvas.grid(column=0, row=0, columnspan=3)
    print(f"non_eng_pic: {self.non_eng_pic}")
    self.canvas_img = self.canvas.create_image(415, 265, image=self.non_eng_pic)
    print(f"non_eng_pic###########: {self.non_eng_pic}")


    This get's printed: non_eng_pic: pyimage

    And then this error is shown:

    Exception in Tkinter callback
    Traceback (most recent call last):
    File "C:\Python312\Lib\tkinter\__init__.py", line 1967, in __call__
    return self.func(*args)
    ^^^^^^^^^^^^^^^^
    File "C:\Users\gabri\OneDrive\Documents\Work\Udemy\100 Days of Python\OOP\Day 31.3 - Improved FlashCard\main.py", line 172, in <lambda>
    main_window = MyMenu(starter_image, lambda: start_flashcards(language, learning_type, vocab))
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Users\gabri\OneDrive\Documents\Work\Udemy\100 Days of Python\OOP\Day 31.3 - Improved FlashCard\main.py", line 107, in start_flashcards
    flashcard_canvas = CanvasSetup(flash_window.window, data_dict, language,
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Users\gabri\OneDrive\Documents\Work\Udemy\100 Days of Python\OOP\Day 31.3 - Improved FlashCard\flashcard.py", line 56, in __init__
    self.canvas_img = self.canvas.create_image(415, 265, image=self.non_eng_pic)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Python312\Lib\tkinter\__init__.py", line 2864, in create_image
    return self._create('image', args, kw)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Python312\Lib\tkinter\__init__.py", line 2850, in _create
    return self.tk.getint(self.tk.call(
    ^^^^^^^^^^^^^
    _tkinter.TclError: image "pyimage3" doesn't exist


    I have tried everything I can think of and searched for answers but nothing gets rid of this error. Please help.

    Continue reading...

Compartilhe esta Página