使用 bind tkinter 检查列表中的哪个按钮被按下

check what button in a list has been pressed with bind tkinter

我有一个按钮列表,当我 运行 一个函数时,我需要检查按下了该列表中的哪个按钮。

import tkinter

root = tkinter.Tk()

def Function(event):
    print('The pressed button is:')

listOfButtons = []
Button = tkinter.Button(root, text="Button 1")
listOfButtons.append(Button)
Button.pack()
Button.bind("<Button-1>", Function)

Button = tkinter.Button(root, text="Button 2")
Button.pack()
listOfButtons.append(Button)
Button.bind("<Button-1>", Function)

root.mainloop()

你可以使用命令

import tkinter

root = tkinter.Tk()

def Function(event):
    if event == 1:
        print('The pressed button is: 1')
    if event == 2:
        print('The pressed button is: 2')

listOfButtons = []
Button = tkinter.Button(root, text="Button 1", command= lambda: Function(1))
listOfButtons.append(Button)
Button.pack()

Button = tkinter.Button(root, text="Button 2",command= lambda: Function(2))
Button.pack()
listOfButtons.append(Button)

root.mainloop()

遍历列表中的所有按钮,并检查 if button is event.widget:

def Function(event):
    for button in listOfButtons:
        if button is event.widget:
            print(button['text'])
            return

正如@tobias_k 提到的那样 - 它过于复杂。您已经有 button 作为 event.widget。所以解决方案很简单 print(event.widget['text'])。但是,如果 Function 不仅可以通过单击按钮调用,或者有多个列表带有 buttons/with 无论如何 - 必须检查!

在另一侧,按钮不仅可以通过鼠标左键单击来按下,因此command选项更好!

import tkinter

root = tkinter.Tk()

def Function(button):
    print(button['text'])


...
Button = tkinter.Button(root, text="Button 1")
Button.configure(command=lambda button=Button: Function(button))
...


Button = tkinter.Button(root, text="Button 2")
Button.configure(command=lambda button=Button: Function(button))
...

root.mainloop()