我正在尝试制作一个5x5的随机生成图像网格。当我运行以下代码时,窗口会以正确的大小弹出,但标签中没有图像:
col = 0
for array in (a,b,c,d,e):
ro = 0
for item in array:
if item == 0:
path = "W.jpg"
elif item == 1:
path = "P.jpg"
elif item == 2:
path = "D.jpg"
elif item == 3:
path = "H.jpg"
elif item == 4:
path = "M.jpg"
elif item == 5:
path = "F.jpg"
img = ImageTk.PhotoImage(Image.open(path))
Label(window, image = img).grid(column = ro, row = col)
ro += 1
col += 1
print(final)
答案 0 :(得分:1)
由于img
将被for循环中的ImageTk.PhotoImage(...)
的新实例覆盖,因此img
的先前引用将丢失并且先前的图像将被破坏。为了克服它,声明一个全局列表来保存图像引用,如下所示:
imagefiles = ['W.jpg', 'P.jpg', 'D.jpg', 'H.jpg', 'M.jpg', 'F.jpg']
images = [] # list to hold the image references
for col, array in enumerate((a, b, c, d, e)):
for ro, item in enumerate(array):
images.append(ImageTk.PhotoImage(Image.open(imagefiles[item]))) # save the image reference
Label(window, image=images[-1]).grid(row=col, column=ro)
或者您可以将图像引用附加到Label实例,如下所示:
imagefiles = ['W.jpg', 'P.jpg', 'D.jpg', 'H.jpg', 'M.jpg', 'F.jpg']
for col, array in enumerate((a, b, c, d, e)):
for ro, item in enumerate(array):
lbl = Label(window)
lbl.grid(row=col, column=ro)
lbl.image = ImageTk.PhotoImage(Image.open(imagefiles[item])) # attach the image reference to label instance variable
lbl.config(image=lbl.image)