我正在尝试使用 python tkinter 创建按钮网格。然后创建一个8X8列表来放置按钮。然后,我想更新单击按钮的文本。我尝试通过传递参数,但是失败了
from tkinter import *
import tkinter.font as tkFont
root = Tk()
font = tkFont.Font(family="helvetica", size=12)
frame=Frame(root)
Grid.rowconfigure(root, 0, weight=1)
Grid.columnconfigure(root, 0, weight=1)
frame.grid(row=0, column=0, sticky=N+S+E+W)
grid=Frame(frame)
grid.grid(sticky=N+S+E+W, column=0, row=7, columnspan=2)
Grid.rowconfigure(frame, 7, weight=1)
Grid.columnconfigure(frame, 0, weight=1)
btn = []
for i in range(8):
temp = []
for j in range(8):
bt = None
temp.append(bt)
btn.append(temp)
def action(x,y):
value = 0
print(x,y)
btn[x][y].configure(text=value ,font=font)
#example values
for x in range(8):
for y in range(8):
print(x,y)
btn[x][y] = Button(frame,width=4,height=2, command= lambda: action(x,y))
btn[x][y].grid(column=x, row=y, sticky=N+S+E+W)
for x in range(8):
Grid.columnconfigure(frame, x, weight=1)
for y in range(8):
Grid.rowconfigure(frame, y, weight=1)
root.mainloop()
无论我单击哪个按钮,它都是更新(7,7)按钮
答案 0 :(得分:0)
您必须将两个参数传递给lambda函数:
像这样:
btn[x][y] = Button(frame, width=4, height=2, command=lambda x=x, y=y: action(x, y))