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.
CodePudding user response:
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()