Search code examples
tkinterphotoimage

ImageTk.PhotoImage gives does not exist message


I am trying to add an image to a canvas. I have stolen the code from a previous forum answer, and it is not working.

    img = Image.open(filename)
    self.currentImage['data'] = img

    photo = ImageTk.PhotoImage(img)
    label = tk.Label(image=photo)
    label.image = photo

    self.c.xview_moveto(0)
    self.c.yview_moveto(0)
    self.c.create_image(0, 0, image=photo, anchor='nw', tags='img')
    self.c.config(scrollregion=self.c.bbox('all'))
    self.currentImage['photo'] = photo

At the create_image line the message "_tkinter.TclError: image "pyimage1" doesn't exist" is produced.

I've read lots of answers to this problem, but all of them are about making a reference, or using lift to change the display order. However I'm not even getting past the creation of the canvas.

What am I missing please?


Solution

  • It looks like you tried to make 2 or more windows in your code by calling tk.Tk() again. The problem with this is that all the variables link to the first root window by default and are not available to the second window.

    The proper fix is to structure your code so that you have a main window that is called with tk.Tk() and all other windows should be started with tk.Toplevel. No program should call tk.Tk() more than once.

    A quick hacky fix is to provide the PhotoImage with the correct master:

    photo = ImageTk.PhotoImage(img, master=self.c)