我有一个按钮列表,当我运行一个函数时,我需要检查该列表中的哪个按钮被按下了。
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()发布于 2017-12-19 17:39:24
遍历列表中的所有按钮,并检查if button is event.widget
def Function(event):
for button in listOfButtons:
if button is event.widget:
print(button['text'])
return正如@tobias_k提到的--它已经被攻克了。您已经有一个作为event.widget的button。所以解决方案很简单,就像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()发布于 2017-12-19 17:39:23
您可以使用命令
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()https://stackoverflow.com/questions/47883821
复制相似问题