0

So I'm new to Tkinter and I thought I'd write a program that starts with the root window, only has 1 button, and when you click that button, a new window appears that opens a specific image, as well as a quit button to close that window. The button in root works and the new window does open, and the quit button in the new window also works, but the image is not there? It's just left blank on the space where there should be that image.

from tkinter import *
from PIL import ImageTk, Image

root = Tk()
root.title("Creating New Windows")
root.iconbitmap("D:/de_clutter/comdes/tkinter/images/__icon_test.ico")

def WINDOWOPEN():
    top = Toplevel()
    img = ImageTk.PhotoImage(Image.open("D:/de_clutter/comdes/tkinter/images/3l3i39em1bu51_256x256.jpg"))
    lbl = Label(top, image = img).pack()
    btn = Button(top, text="Quit", command=top.destroy).pack()
    return

openWindowButton = Button(root, text = "Open Image", command = WINDOWOPEN).pack()


mainloop()

The image does exist btw

1 Answers1

0

You need to keep the reference. To do that you need to use the widget object, which means you can't put the layout on the same line as the definition (you shouldn't do that anyway). Try this:

def WINDOWOPEN():
    top = Toplevel()
    img = ImageTk.PhotoImage(Image.open("D:/de_clutter/comdes/tkinter/images/3l3i39em1bu51_256x256.jpg"))
    lbl = Label(top, image = img)
    lbl.pack()
    lbl.image = img # keep the image reference
    btn = Button(top, text="Quit", command=top.destroy)
    btn.pack()
Novel
  • 13,406
  • 2
  • 25
  • 41