【问题标题】:check what button in a list has been pressed with bind tkinter使用 bind tkinter 检查列表中的哪个按钮被按下
【发布时间】:2024-04-23 12:40:02
【问题描述】:

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

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

【问题讨论】:

  • 您不需要在按钮上使用bind,只需在创建按钮时使用它们的command 选项。
  • 不仅你不需要使用bind,而且你限制你的按钮能够运行Function,当且仅当它被按下鼠标左键时。

标签: python button tkinter bind


【解决方案1】:

遍历列表中的所有按钮,并检查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 不仅可以通过单击按钮调用,或者有多个带有按钮/任何内容的列表 - 必须检查!

另一方面,按钮不仅可以通过鼠标左键单击,因此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()

【讨论】:

  • 因为print(event.widget['text']) 太容易了?
  • @tobias_k 这是一个很好的解决方案,同时也是提出改进建议的一种奇怪方式。
  • @tobias_k,是的,你是对的。我“想多了”按下了列表中的哪个按钮
【解决方案2】:

你可以使用命令

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

【讨论】:

  • 你需要做command= lambda: Function(1)否则,你在按钮创建时执行该功能,而不是在点击时。
  • 你是对的,我更正了。我以为出了点问题,在*.com/questions/6920302/…找到了答案并看到了命令:D