Tkinter - 使用 for 循环显示多个图像
Tkinter - use for loop to display multiple images
我正在尝试向 window 显示多张图片(作为标签),但只显示最后一张图片
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()
每次在循环中重新赋值img
,上一张图片的数据都会被破坏,无法再显示。要解决此问题,请将图像添加到列表以永久存储它们:
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()
我正在尝试向 window 显示多张图片(作为标签),但只显示最后一张图片
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()
每次在循环中重新赋值img
,上一张图片的数据都会被破坏,无法再显示。要解决此问题,请将图像添加到列表以永久存储它们:
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()