检查列表中的哪个按钮已用bind tkinter按下 [英] check what button in a list has been pressed with bind tkinter
问题描述
我有一个按钮列表,当我运行一个函数时,我需要检查该列表中的哪个按钮被按下.
I have a list of buttons and when I run a function I need to check what button in that list was pressed.
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()
推荐答案
遍历列表中的所有按钮,并检查按钮是否为event.widget
:
Iterate over all buttons in the list, and check 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
,或者有多个带有按钮的列表或其他内容-这是必须检查的!
As @tobias_k mentioned - it's overcomlicated. You already has a button
as event.widget
. So solution is simple as print(event.widget['text'])
. However, if Function
can be called not only from the button click or there're several lists with buttons/with whatever - it's a must to check!
另一方面,不仅可以通过鼠标左键单击按钮,因此 command
选项更好!
In other side, button can be pressed not only by the Left-mouse click, hence command
option is better!
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()
这篇关于检查列表中的哪个按钮已用bind tkinter按下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!