Python tkinter查找单击的按钮

2024-10-01 09:32:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试实现一个叫做“五连冠”的游戏。 我创建了一个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?。但我不太明白。在


Tags: textinobjforrangebuttonrootwidth
2条回答

使用command = p(obj)时,实际上是在调用函数p。如果要传递带参数的函数,则应创建lambda函数。因此,命令分配应该类似于:

command = lambda: p(obj)

将对象正确地传递到p函数中。在

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

例如:

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

相关问题 更多 >