0

I don't know why the image not showing.
Is this a device problem or some update in the Tkinter library?

from tkinter import *
root = Tk()
btn = Button(master=root,image=PhotoImage(file='Sample1.png'))
btn.pack()


root.mainloop()

Sample Image:

enter image description here

enter image description here

codester_09
  • 5,622
  • 2
  • 5
  • 27
  • 2
    It is because there is no variable reference the image, so the image will be garbage collected. Use a variable to store the image reference. – acw1668 Aug 07 '22 at 15:12
  • Does this answer your question? [Why does Tkinter image not show up if created in a function?](https://stackoverflow.com/questions/16424091/why-does-tkinter-image-not-show-up-if-created-in-a-function) – Art Aug 07 '22 at 23:29

1 Answers1

2

When a PhotoImage object is garbage-collected by Python (e.g. when you return from a function which stored an image in a local variable), the image is cleared even if it’s being displayed by a Tkinter widget.

Python garbage-collects any local objects at the end of the scope, even when being used by a Tkinter widget. To prevent this, you need to assign the image to some variable:

photoimage = PhotoImage(file='Sample1.png')
btn = Button(master=root,image=photoimage)

Related: Tkinter vanishing PhotoImage issue

ignassew
  • 83
  • 5