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.
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 7 lines.
class CanvasSetup:
dutch_word = ""
eng_word = ""
counter = 1
pic_list = []
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")
CanvasSetup.pic_list.append(self.eng_pic)
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")
CanvasSetup.pic_list.append(self.non_eng_pic)
else:
self.non_eng_pic = PhotoImage(file="card_front2.png")
CanvasSetup.pic_list.append(self.non_eng_pic)
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: {CanvasSetup.pic_list[1]}")
try:
self.canvas_img = self.canvas.create_image(415, 265, image=CanvasSetup.pic_list[1])
except Exception as e:
print(e)
print(f"non_eng_pic###########: {CanvasSetup.pic_list[1]}")
The first print statement prints:
“non_eng_pic: pyimage3”
Then the ‘try:’ block errors out so the ‘except:’ block gets printed:
“image “pyimage3” doesn’t exist”
But then the final print statement prints:
“non_eng_pic###########: pyimage3”
So, the image is not getting garbage collected. What am I doing wrong? I have tried everything I can think of and searched for answers but nothing gets rid of this error. Please help.