将参数传递给tkinter按钮的命令

时间:2019-06-25 05:05:15

标签: python-3.x tkinter

我正在尝试使用 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)按钮

1 个答案:

答案 0 :(得分:0)

您必须将两个参数传递给lambda函数:

像这样:

btn[x][y] = Button(frame, width=4, height=2, command=lambda x=x, y=y: action(x, y))