标签:python for-loop image 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()
任何有关如何使其工作的建议将不胜感激.
解决方法:
这是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
标签:python,for-loop,image,tkinter,label 来源: https://codeday.me/bug/20191003/1846557.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。