Python tkinter查找单击了哪个按钮 [英] Python tkinter find which button is clicked

查看:64
本文介绍了Python tkinter查找单击了哪个按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to implement a game called "Five In a Row". And I create a 15×15 list to put the buttons. (I used range(16) because I also want a row and a column to display the row number and column number)

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

I hope my implementation will be like when a button is clicked, it becomes a label. But I don't know which button the user clicks.

我该如何实现?谢谢!

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()

有一个类似的问题 如何确定在 Python TKinter 中的按钮网格中按下了哪个按钮?.但我不太明白.

There is a similar question How to determine which button is pressed out of Button grid in Python TKinter?. But I don't quite get that.

推荐答案

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

To pass the button instance to the command, you must do it in two steps. First, create the button, and then in a second step you configure the command. Also, you must use a lambda to create what's called a closure.

例如:

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

这篇关于Python tkinter查找单击了哪个按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆