0
import tkinter as tk
from tkinter import ttk


def picture():

    window2 = tk.Toplevel()
    window2.title("Window2")
    window2.geometry("300x300")
    window2.configure(background='grey')

    f =  "C:\\Users\\Bob\\Documents\\Python\\bb.gif"
    img = tk.PhotoImage(file =f)

    panel = ttk.Label(window2, width= 100, background = "green", image =img)
    panel.grid(column=1, row=1, sticky=(tk.W,tk.E))

#Start the GUI

window = tk.Tk()
window.title("Window1")
window.geometry("300x300")
window.configure(background='grey')

f =  "C:\\Users\\Bob\\Documents\\Python\\bb.gif"
img = tk.PhotoImage(file = f)

panel = ttk.Label(window, width= 100, background = "green", image =img)
panel.grid(column=1, row=1, sticky=(tk.W,tk.E))
picture()

window.mainloop()

In the above code, Why does the picture display in window1 but not window2? It works if the image is passed as a parameter to the function! running with Python3.

j_4321
  • 15,431
  • 3
  • 34
  • 61
lyndalebob
  • 1
  • 1
  • 1

1 Answers1

1

The variable img is a local variable to the function picture() which gets garbage collected after the functin exits. Save a reference to the photo, for example:

panel.image = img

as the last line in the function.

figbeam
  • 7,001
  • 2
  • 12
  • 18