There are a few related questions about label image been garbage collected. People usually suggest keep a reference to the photo label.image = photoImage
to prevent gc. But I'm still confused. I thought when creating Label object
labelImg = tk.Label(window, image=photoImage, width=81, height=81)
photo image is passed as a parameter, so labelImg
object should already has a reference to it.
If it does not, what does the constructor do to the passed-in potoImage
object?
Here is an exmaple code:
import tkinter as tk
from PIL import Image, ImageTk
window = tk.Tk()
window .geometry('400x510')
window.resizable(0, 0)
for n in range(5):
image = Image.open('img.jpg')
photoImage = ImageTk.PhotoImage(image.resize((81, 81)))
labelImg = tk.Label(window, image=photoImage, width=81, height=81)
labelImg.place(relx=0, rely=0.2*n)
# labelImg.image = photoImage without this line, only last photo image is shown.
window.mainloop()