Search on blog:

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

Flask: Jak wyświetlić obraz bez zapisywania go w pliku korzystając z BytesIO oraz obrazu w postaci stringu BASE64 w url

Można użyć BytesIO do stworzenia obiektu podobnego do pliku (file-like object) ale trzymanego w pamięci RAM, który może być użyty do działań na pliku obrazka bez zapisywania na dysku.

Ten przykład używa matplotlib do stworzenia PNG w pamięci

import io
import matplotlib.pyplot as plt
import random

def generate_image():

    # genereate …

« Page: 1 / 1 »