1

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()
Xiaoyong Guo
  • 361
  • 1
  • 7
  • If you are talking of `labelImg` then it is a label of width and height 81 to which you have provided image instead of text. – Tanishka May 29 '21 at 16:26
  • 1
    `tkinter` doesn't work the way you think — it does **not** create a reference to the photo image — that is why you need to do it yourself. In this case just add a `labelImg.img = photoImage` after creating the `Label`. – martineau May 29 '21 at 17:24
  • @TanishkaVashisht: [`Label`](https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/label.html) widgets may also have an image. – martineau May 29 '21 at 17:30
  • @martineau I think so. I may need to look into the code to see how Label object is contructed. – Xiaoyong Guo May 30 '21 at 00:37
  • 1
    If it's created in some function (or method), see [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). This is a common problem and is because basically there what I would consider a bug in `tkinter` in this regard. – martineau May 30 '21 at 00:55

0 Answers0