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

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

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

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


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5431481.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存