使用tkinter使用for语句在标签中显示图片,是否可以完成?

时间:2013-10-20 17:49:03

标签: python image for-loop tkinter label

我正试图将一堆随机图片并排打印出来;问题是,如果我运行以下代码,所有发生的事情是它创建一组空白空标签。如果我用“text ='what'”替换'image = pic',它可以正常工作(从而证明它实际上创建了标签)。将标签和图像放置在其他任何地方工作正常(证明它不是图像),即使我使用'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()

非常感谢任何有关如何使其发挥作用的建议。

1 个答案:

答案 0 :(得分:4)

这是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