使用Tkinter,我有很多按钮。我希望每次按下任何按钮时都触发相同的回调函数。我如何找出按下了哪个按钮?
def call(p1):
# Which Button was pressed?
pass
for i in range (50):
B1 = Button(master, text = '...', width = 2)
B1.grid(row = i*20, column = 60)
B1.bind('<Button-1>',call)
B2 = Button(master, text = '...', width = 2)
B2.grid(row = i*20, column = 60)
B2.bind('<Button-1>',call)
Run Code Online (Sandbox Code Playgroud)
使用列表来引用动态创建的按钮,并使用lambda来存储对按钮对象的索引的引用。您可以确定单击了哪个按钮。在下面的示例中,我使用.cget("text")按钮对象来演示如何访问按钮小部件。
import tkinter as tk
root = tk.Tk()
root.minsize(200, 200)
btn_list = [] # List to hold the button objects
def onClick(idx):
print(idx) # Print the index value
print(btn_list[idx].cget("text")) #Print the text for the selected button
for i in range(10):
# Lambda command to hold reference to the index matched with range value
b = tk.Button(root, text = 'Button #%s' % i, command = lambda idx = i: onClick(idx))
b.grid(row = i, column = 0)
btn_list.append(b) # Append the button to a list
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用bind,然后从生成的事件对象访问窗口小部件。
import tkinter as tk
root = tk.Tk()
root.minsize(200, 200)
def onClick(event):
btn = event.widget # event.widget is the widget that called the event
print(btn.cget("text")) #Print the text for the selected button
for i in range(10):
b = tk.Button(root, text = 'Button #%s' % i)
b.grid(row = i, column = 0)
# Bind to left click which generates an event object
b.bind("<Button-1>", onClick)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)