如何解决Tkinter-使用循环创建按钮及其图像
有没有一种方法可以使用循环创建具有唯一图像和标识的按钮?我想出了下面的代码,但是只有一个能起作用并且具有图像的按钮是最后一个:
import tkinter as tk
from tkinter import *
from functools import partial
win = tk.Tk()
win.geometry('800x500') # set window size
dic = {0: {"row": 0,"col": 0 },1: {"row": 1,2: {"row": 2,"col": 0 }}
chairImg,chair2Img,checkImg = None,None,None
fileList = [chairImg,checkImg]
imgList = ['chair.png','chair2.png','check.png']
buttonIdentities = []
i=0
def checkButton(n):
# function to get the index and the identity (bname)
print(n)
bname = (buttonIdentities[n])
for img,f in zip(imgList,fileList):
f = PhotoImage(file=img)
f = f.zoom(16).subsample(256)
button = Button(win,image=f,command=partial(checkButton,i))
button.grid(row=dic[i]['row'],column=dic[i]['col'])
buttonIdentities.append(button)
i+=1
print(button_identities)
win.mainloop()
我想简化代码,因为我将在我的应用程序中使用更多按钮和图像。谢谢您的时间和答复。
解决方法
由于垃圾收集,图像似乎丢失了。 为避免这种情况,只需添加对图像的引用,如下所示:
button = Button(win,image=f,command=partial(checkButton,i))
button.image = f #This line here.
button.grid(row=dic[i]['row'],column=dic[i]['col'])
(不必是.image
,可以是任何东西)
通过保留对图像的引用,不会收集垃圾。您可以详细了解here。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。