pythontkinterpython-imaging-libraryphotoimage

Python problem showing image in label in secondary window


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 Slideshow\01001-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:

  1. The code works if the label is in the main window, just not if it's in the secondary window.
  2. 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.
  3. 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.


Solution

  • Python problem showing image in label in secondary window

    Any ideas? Has anyone successfully put an image into a secondary window in Python?

    The problem can be fixed.

    Use Toplevel() to open a new window.

    Change this:

    window2 = Tk()
    

    To:

    window2 = Toplevel()
    

    Screenshot: You can see tile on the second window.

    enter image description here