This problem is one of many posted here where there’s an error because the image created by PhotoImage doesn’t exist. Consider this code:
from tkinter import *
from PIL import ImageTk
def show():
path = r'P:Greece Slideshow1001-MJR_20240511_5110080-Edit.jpg'
pimg = ImageTk.PhotoImage(file=path)
image_label.configure(image=pimg)
root.pimg = pimg # prevent garbage collection
root = Tk()
window2 = Tk()
# image_label = Label(root) # works if label is in main window
image_label = Label(window2) # fails if label is in secondary window
# message is "_tkinter.TclError: image "pyimage1" doesn't exist"
image_label.pack()
root.after(500, show)
root.mainloop()
Three things to note:
- The code works if the label is in the main window, just not if it’s in the secondary window.
- As shown, I’ve assigned the PhotoImage to root.pimg so it won’t be garbage collected. I’ve tried numerous variants of this (e.g., global variable, property of other persistent objects), but nothing helps.
- I’ve tried a Canvas instead of a Label, but I get exactly the same error message.
Any ideas? Has anyone successfully put an image into a secondary window in Python? I don’t have to use PIL; anything at all will make me happy. I hate to go down to the level of the Win32 API (kills portability), but I’m about to do that.