Python Forum

Full Version: What can the event.widget reference be used for?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Widgets bound with self.root.bind_all("", lambda e: self.focus(e)) return a widget reference through e.widget such as ".!entry2" when a widget receives the focus.

I can't find anywhere how this notation can be used to identify or access the particular widget receiving the focus. I'm sure it can be done otherwise it wouldn't be useful to report this value.

How does one use ".!entry2" to access the associated widget?
When the event is triggered, you can use:
print(vars(event))
which will show a dictionary, something like:
Output:
{'serial': 178, 'num': 1, 'height': '??', 'keycode': '??', 'state': 16, 'time': 1126658485, 'width': '??', 'x': 93, 'y': 20, 'char': '??', 'send_event': False, 'keysym': '??', 'keysym_num': '??', 'type': <EventType.ButtonPress: '4'>, 'widget': <tkinter.Button object .!button>, 'x_root': 986, 'y_root': 548, 'delta': 0}
(Aug-26-2021, 01:41 AM)Larz60+ Wrote: [ -> ]When the event is triggered, you can use:
print(vars(event))
which will show a dictionary, something like:
Output:
{'serial': 178, 'num': 1, 'height': '??', 'keycode': '??', 'state': 16, 'time': 1126658485, 'width': '??', 'x': 93, 'y': 20, 'char': '??', 'send_event': False, 'keysym': '??', 'keysym_num': '??', 'type': <EventType.ButtonPress: '4'>, 'widget': <tkinter.Button object .!button>, 'x_root': 986, 'y_root': 548, 'delta': 0}

I hadn't run into vars() so it's good to know. It provides a lot more info. Thanks! Unfortunately, I don't see any kind of object reference that would allow me to do something like widget_in_focus = get_widget_by_id(event.widget_id).

I do have a tracking list hack, but I'd rather not lean on it. I'm sure I'm just missing something, but I can't find it I'm curious about the notation .!entry2. Why the dot bang?
(Aug-26-2021, 05:22 AM)Yoriz Wrote: [ -> ]Refer to tkinter widget by its instance

Bingo and Yahtzee! This solution is perfect.

The function nametowidget(event.widget) is streamlined for interrogating the details of the widget receiving focus.

Many thanks!