python tkinter用于循环使用和图像未加载 [英] python tkinter for loop used and image not loading
问题描述
我的图像未加载。我不知道。这是我的代码的一部分。我的图像尺寸在高度和宽度上都较小。出于某种原因,也仅显示最后一张图像:
My image is not loading. I have no idea. Here is part of my code. The size of my image are small in height and width. Also only the last image shows for some reason:
lenlist1 = len(list1)
""" Displays text and photo """
for i in range(lenlist1):
name = list1[i]
Pic = Piclist[i]
height = i * 400
canvas.create_text(1,height,text=name,anchor=tkinter.NW)
pic = tkinter.PhotoImage(file = Pic)
root.pic = pic
height2 = (i*400) + 20
canvas.create_image(1,height2,image=pic, anchor = tkinter.NW)
frame.pack()
推荐答案
每次通过该循环,变量 pic
被分配一个新的 tkinter.PhotoImage
对象。如果附加到该名称的先前对象没有其他引用,则将对其进行垃圾收集。如所述此处:
Each time through that loop, the variable pic
is assigned a new tkinter.PhotoImage
object. If the previous object that was attached to that name has no other references to it, it is garbage-collected. As stated here:
您必须在Python程序中保留对图像对象的引用,方法是将其存储在全局变量中或将其附加到另一个对象。
You must keep a reference to the image object in your Python program, either by storing it in a global variable, or by attaching it to another object.
当PhotoImage对象被Python垃圾回收时(例如,当您从将图像存储在局部变量中的函数返回时),即使Tkinter小部件正在显示该图像,也会清除该图像。
When a PhotoImage object is garbage-collected by Python (e.g. when you return from a function which stored an image in a local variable), the image is cleared even if it’s being displayed by a Tkinter widget.
为避免这种情况,程序必须保留对图像对象的额外引用。
To avoid this, the program must keep an extra reference to the image object.
,您可以将每个 pic
附加到列表中,以便每个图像始终都有对其的引用。
For example, you could append each pic
to a list so that each image always has a reference to it.
这篇关于python tkinter用于循环使用和图像未加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!