使用tkinter在带有for语句的标签中显示图片,可以吗?

发布于 2021-01-29 15:02:23

我正在尝试随机打印一堆图片;问题是,如果我运行以下代码,那么所有发生的就是它会创建一组空白的空标签。如果我将“ image = pic”替换为“ text
=’whatever’”,则效果很好(因此证明它确实创建了标签)。即使我使用’pic = PhotoImage(file = w
[0])’,也可以将标签和图像放置在其他任何地方(证明它不是图像)也可以正常工作(因此,我认为它不是我的方法)。 。

from tkinter import *
from tkinter import ttk
import random

root = Tk()
root.title("RandomizedPic")

def randp(*args):
    w = ['wb.gif', 'wc.gif', 'wd.gif', 'we.gif']
    random.shuffle(w)
    am = 1

    for i in w:
        pic = PhotoImage(file=i)
        ttk.Label(mainframe, image=pic).grid(column=am, row=0, sticky=(W, E))
        am+=1


mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)

ttk.Button(mainframe, text="Do it", command=randp).grid(column=0, row=0, sticky=W)

root.bind('<Return>', randp)
root.mainloop()

任何有关如何使其正常工作的建议将不胜感激。

关注者
0
被浏览
65
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    这是tkinter的一个众所周知的问题-您必须保留对所有Photoimages的引用,否则python将对其进行垃圾回收-
    这就是您的图像所发生的事情。仅将它们设置为标签的图像不会增加图像对象的引用计数。

    解:

    要解决此问题,您将需要对创建的所有图像对象的持久引用。理想情况下,这将是类命名空间中的数据结构,但是由于您未使用任何类,因此模块级列表将必须执行:

    pics = [None, None, None, None]   #  This will be the list that will hold a reference to each of your PhotoImages.
    
    def randp(*args):
        w = ['wb.gif', 'wc.gif', 'wd.gif', 'we.gif']
        random.shuffle(w)
        am = 1
    
        for k, i in enumerate(w):    # Enumerate provides an index for the pics list.
            pic = PhotoImage(file=i)
            pics[k] = pic      # Keep a reference to the PhotoImage in the list, so your PhotoImage does not get garbage-collected.
            ttk.Label(mainframe, image=pic).grid(column=am, row=0, sticky=(W, E))
            am+=1
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看