Python 3.x Tkinter-使用循环创建按钮及其图像
有没有办法使用循环创建每个按钮,每个按钮都具有唯一的图像和标识?我想出了下面的代码,但只有最后一个按钮可以工作并有它的图像:Python 3.x Tkinter-使用循环创建按钮及其图像,python-3.x,tkinter,Python 3.x,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:
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, "col": 0 }, 2: {"row": 2, "col": 0 }}
chairImg, chair2Img, checkImg = None, None, None
fileList = [chairImg, chair2Img, 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
,它可以是任何东西)通过保留对映像的引用,它不会被垃圾收集。你可以阅读更多关于它的内容