Tkinter - 多个按钮相同的事件 [英] Tkinter - Same event for multiple buttons
问题描述
使用Tkinter,我有很多按钮。每次按下任何按钮时,我都希望触发相同的回调函数。如何找到按下哪个按钮?
Using Tkinter, I have many buttons. I would like the same callback function to be triggered every time any of the buttons pressed. How can I find out which button was pressed ?
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)
推荐答案
使用列表引用动态创建的按钮和lambda来存储对索引的引用的按钮对象。您可以确定点击了哪个按钮。在下面的例子中,我使用按钮对象上的 .cget(text)
来演示访问按钮小部件。
Using a list to reference the dynamically created buttons and lambda to store a reference to the index of the button object. You can determine which button was clicked. In the below examples I use .cget("text")
on the button object to demonstrate accessing the button widget.
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()
或者,您可以使用绑定,然后从生成的事件对象访问窗口小部件。
Alternatively you can use bind and then access the widget from the event object generated.
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()
这篇关于Tkinter - 多个按钮相同的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!