Python tkinter find which button is clicked

落花浮王杯 提交于 2021-02-16 09:01:22

问题


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.

How am I able to implement that? Thanks!

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

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.


回答1:


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.

For example:

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



回答2:


When you use command = p(obj) you are actually calling the function p. If you want to pass a function with parameters you should create a lambda function. Therefore, the command assignment should be something like:

command = lambda: p(obj)

That will pass the object properly into p function.



来源:https://stackoverflow.com/questions/47295740/python-tkinter-find-which-button-is-clicked

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!