Tkinter: Why Label doesn't display image? Bug with Garbage Collector in PhotoImage.
Sometimes image can disappear when you move code into function.
It is common problem with bug in PhotoImage
with garbage collector
which removes image from memory when image is assigned to local variable (variable created in function). You have to assign image to global
variable or to some object - ie. to Label
which displays this image.
Example which uses global
import tkinter as tk # PEP8: `import *` is not preferred
def main(root):
global img # <-- solution for bug
img = tk.PhotoImage(file="image.png")
label = tk.Label(image=img)
label.pack()
if __name__ == "__main__":
root = tk.Tk()
main(root)
root.mainloop()
Example which uses Label
object
import tkinter as tk # PEP8: `import *` is not preferred
def main(root):
img = tk.PhotoImage(file="image.png")
label = tk.Label(image=img)
label.pack()
label.img = img # <-- solution for bug
if __name__ == "__main__":
root = tk.Tk()
main(root)
root.mainloop()
Not so long time ago you could find this information in popular documentation for tkinter on effbot.org but now this documentation disappeared.
I found old effbot.org in Wayback Machine from 2020.11.12: PhotoImage