Python tkinter 找到点击了哪个按钮

标签 python tkinter

我正在尝试实现一个名为“五连胜”的游戏。 我创建了一个 15×15 的列表来放置按钮。 (我用range(16)是因为我也想要一行一列来显示行号和列号)

我希望我的实现就像单击按钮时一样,它会变成标签。 但我不知道用户点击了哪个按钮。

我怎样才能实现它?谢谢!

from tkinter import *
root=Tk()
root.wm_title("Five In a Row")
buttonlst=[ list(range(16)) for i in range(16)]

chess=Label(root,width=2,height=2,text='0')

def p(button):
    gi=button.grid_info()
    x=gi['row']
    y=gi['column']
    button.grid_forget()
    chess.grid(row=x,column=y)
    buttonlst[x][y]=chess

for i in range(16):
    for j in range(16):
        if i==0:
            obj=Label(root,width=2,text=hex(j)[-1].upper())
        elif j==0:
            obj=Label(root,width=2,text=hex(i)[-1].upper())
        else:
            obj=Button(root,relief=FLAT,width=2,command=p(obj))
        obj.grid(row=i,column=j)
        buttonlst[i][j]=obj

root.mainloop()

有个类似的问题How to determine which button is pressed out of Button grid in Python TKinter? .但我不太明白。

最佳答案

要将按钮实例传递给命令,您必须分两步完成。首先,创建按钮,然后在第二步中配置命令。此外,您必须使用 lambda 来创建所谓的闭包

例如:

obj=Button(root,relief=FLAT,width=2)
obj.configure(command=lambda button=obj: p(button))

关于Python tkinter 找到点击了哪个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47295740/

相关文章:

python - 如何使用 Tkinter 创建等宽网格列?

python - osx 上的 Tkinter/matplotlib 多个事件窗口

python - 远程运行 TensorFlow

python - 如何使用 %pythonappend 和 %pythonprepend 访问 SWIG 中的参数和返回值?

python - 将数组的 Python 字典转换为数据框

python - 喘息模板字典变量查找

python - 使用标准 'close' 按钮关闭 easygui Python 脚本

python - 如何在 Tkinter Canvas 中为子字符串着色

python - 从 Tkinter 打印 Canvas

python - 传送某些 python 函数的文档字符串