【发布时间】:2020-08-20 09:07:54
【问题描述】:
有没有办法使用循环创建每个具有唯一图像和身份的按钮?我想出了下面的代码,但唯一有效的按钮是最后一个:
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()
我很想简化我的代码,因为我将在我的应用程序中使用更多按钮和图像。感谢您的时间和回答。
【问题讨论】:
标签: python-3.x tkinter