Search code examples
pythonloopstkinterlabelpython-imaging-library

Tkinter - use for loop to display multiple images


I am trying to display multiple images (as labels) to the window but only the last images is displayed

from tkinter import *
from PIL import ImageTk, Image

root = Tk()

f = open("data/itemIDsList.txt")
ids = []
for line in f:
    line = line.rstrip("\n")
    ids.append(line)
f.close()

for i in range(10):
    img = ImageTk.PhotoImage(Image.open(f"website/images/{ids[i]}.png"))
    Label(root, image=img, width=60, height=80).grid()

root.mainloop()

Solution

  • Each time you reassign img in the loop, the data of the previous image gets destroyed and can no longer be displayed. To fix this, add the images to a list to store them permanently:

    from tkinter import *
    from PIL import ImageTk, Image
    
    root = Tk()
    
    f = open("data/itemIDsList.txt")
    ids = []
    for line in f:
        line = line.rstrip("\n")
        ids.append(line)
    f.close()
    
    imgs = []
    for i in range(10):
        imgs.append(ImageTk.PhotoImage(Image.open(f"website/images/{ids[i]}.png")))
        Label(root, image=imgs[-1], width=60, height=80).grid()
    
    root.mainloop()