Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 732
logan_9997 Avatar asked Sep 07 '25 23:09

logan_9997


1 Answers

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()
like image 154
Lecdi Avatar answered Sep 10 '25 07:09

Lecdi