1
from tkinter import *
from PIL import ImageTk, Image

root = Tk()
nameList = ["images/icons/first.bmp", "images/icons/second.bmp"]
ycord = 0
for execute in nameList:
    myimg = ImageTk.PhotoImage(Image.open(execute))
    Label(image=myimg).place(x=0, y=0)
    ycord += 80

root.mainloop()

With this code, for some reason the first.bmp doesnt get shown in the tkinter window. Only the second.bmp does appear.

  • 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) – jasonharper Jul 11 '22 at 01:13
  • (Not exactly the same situation, but it's the same root cause.) – jasonharper Jul 11 '22 at 01:14
  • Not sure if it does answer my question. Answers suggest using `global` ( i dont have a def here) or use `self.` which i dont have a class. – Giannis Tsakas Jul 11 '22 at 01:21
  • It is because you use same variable `myimg` to store the references of images, so only the last image is being referenced and those other images are garbage collected. One of the way is use an attribute of the label to store the reference of the image. – acw1668 Jul 11 '22 at 01:32
  • I really do get the logic of what you are saying here but I still cant see a way. Still trying – Giannis Tsakas Jul 11 '22 at 01:40

1 Answers1

2

It is because you use same variable myimg to store the references of images, so only the last image is being referenced and those other images are garbage collected. One of the way is use an attribute of the label to store the reference of the image.

from tkinter import *
from PIL import ImageTk, Image

root = Tk()
nameList = ["images/icons/first.bmp", "images/icons/second.bmp"]
ycord = 0
for execute in nameList:
    myimg = ImageTk.PhotoImage(file=execute)
    lbl = Label(root, image=myimg)
    lbl.place(x=0, y=ycord)
    lbl.image = myimg  # use an attribute of label to store the reference of image
    ycord += 80

root.mainloop()
acw1668
  • 40,144
  • 5
  • 22
  • 34