已使用python tkinter for循环且未加载图像

2024-05-03 05:05:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我的图像没有加载。我不知道。这是我的部分代码。我的图像大小在高度和宽度上都很小。此外,由于某些原因,只有最后一张图像显示:

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()

Tags: textname图像imagetkintercreatecanvasanchor
1条回答
网友
1楼 · 发布于 2024-05-03 05:05:03

每次通过该循环时,变量pic都被分配一个新的tkinter.PhotoImage对象。如果附加到该名称的上一个对象没有其他引用,则该对象将被垃圾收集。如here所述:

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.

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附加到一个列表中,这样每个图像总是有一个对它的引用

相关问题 更多 >