[Tutor] Finding the widget name which generated an event
Alan Gauld
alan.gauld at blueyonder.co.uk
Tue May 6 17:10:16 EDT 2003
> how can i find the widget name that generated an
> event?
Technically the widget doesn't have a name.
Instead there is a variable in your code that references
the widget. You could have several names referring to
the same widget, in which case which name gets printed?
e = Entry(rt)
e1 = Entry(rt)
e2 = e1
Now does the event on e1 widget print 'e1' or 'e2' since
both are valid names for the same object!
More pragmatically...
> widget rather than widget name. How can i get the
> widget name that generated an event?
> My coding is given below.
>
> import Tkinter
> def gotFocus(event):...
> def lostFocus(event):...
>
> root = Tkinter.Tk()
>
> e = Tkinter.Entry()
> e1=Tkinter.Entry()
You should really pass a parent to the widgets:
e = Tkinter.Entry(root)
But that doesn't buy you much here.
If you want to have some kind of friendly name printed then
you need to store the widgets in a dictionary or class:
widgets = {}
widgets['e'] = Entry(root)
widgets['e1'] = Entry(root)
Now you can compare the widget id with the objects in
the dictionary:
for key in widgets.keys():
if id(e.widget) == id(widgets[key]):
print "Widget: ", key
Another option involves setting setting separate
callbacks for each widget:
def gotFocus(event, name):
print "Widget: ", name
e.bind('<FocusIn>', lambda ev,nm='e': gotFocus(ev,nm) )
e1.bind('<FocusIn>', lambda ev,nm='e1': gotFocus(ev,nm) )
HTH,
Alan G.
(Back from a very wet vacation!)
More information about the Python-list
mailing list