-1

How come I can't add images using this:

from tkinter import * 
root = Tk()

def logo():
    photo = PhotoImage(file="Logo.png")
    Label(root, image=photo).grid()

logo()

root.mainloop()

But I can add images using this:

from tkinter import * 
root = Tk()

photo = PhotoImage(file="Logo.png")
Label(window, image=photo).grid()

logo()

root.mainloop()

Any help?

B.Bacon
  • 3
  • 2
  • Your variable `photo` is garbage collected the moment you exit the function `logo`; you need to keep a reference to it in the global space, or as an attribute of a class. – Reblochon Masque Aug 22 '18 at 23:17

1 Answers1

0

You have to keep a reference to the image to prevent it being garbage collected. Try this:

def logo():
    photo = PhotoImage(file="Logo.png")
    lbl = Label(root, image=photo)
    lbl.image = photo # keep a reference
    lbl.grid()

You don't have to do that in your other block because you are using global variables, which are never garbage collected.

See the note on the bottom of this page.

Novel
  • 13,406
  • 2
  • 25
  • 41