我正在嘗試在視窗中顯示多個影像(作為標簽),但只顯示最后一個影像
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()
uj5u.com熱心網友回復:
每次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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/462033.html
