Tkinter vanishing PhotoImage issue [duplicate]

You need to keep an additional reference to photo so it doesn’t get prematurely garbage collected at the end of the function. An Introduction to Tkinter explains further:

Note: When a PhotoImage object is garbage-collected by Python (e.g. when you return from a function which stored an image in a local variable), the image is cleared even if it’s being displayed by a Tkinter widget.

To avoid this, the program must keep an extra reference to the image object. A simple way to do this is to assign the image to a widget attribute, like this:

label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()

In your case, you could attach the image to your self variable, or maybe the canvas. It doesn’t really matter, as long as it is assigned to something.

self.image = photo
#or:
self.__canvas3.image = photo

Leave a Comment