In Tkinter, I have a multiple widgets bound to the left-mouse button. They all trigger the same event when clicked.
How do I recover which widget was clicked?
I want it so when say Label2
was pressed, I'd be able to recover that Label2
was the widget that was pressed within the event it triggered.
def f(event):
caller = event.widget
You have a couple options. One way is to access the widget
attribute of the event object. Another way is to pass an object reference in to your function. Here's an example that uses one of each.
import Tkinter as tk
def onClickA(event):
print "you clicked on", event.widget
event.widget.config(text="Thank you!")
def onClickB(event, obj):
print "you clicked on", obj
obj.config(text="Thank you!")
root = tk.Tk()
l1 = tk.Label(root, text="Click me")
l2 = tk.Label(root, text="No, click me!")
l1.pack()
l2.pack()
l1.bind("<1>", onClickA)
l2.bind("<1>", lambda event, obj=l2: onClickB(event, obj))
root.mainloop()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With