Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the widget that triggered an Event?

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.

like image 807
rectangletangle Avatar asked Nov 28 '10 21:11

rectangletangle


2 Answers

def f(event):
    caller = event.widget
like image 79
cag Avatar answered Oct 29 '22 16:10

cag


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()
like image 40
Bryan Oakley Avatar answered Oct 29 '22 14:10

Bryan Oakley