Python Forum
[Tkinter] What can the event.widget reference be used for? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: GUI (https://python-forum.io/forum-10.html)
+--- Thread: [Tkinter] What can the event.widget reference be used for? (/thread-34731.html)



What can the event.widget reference be used for? - Knickers - Aug-25-2021

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?


RE: What can the event.widget reference be used for? - Larz60+ - Aug-26-2021

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}



RE: What can the event.widget reference be used for? - Knickers - Aug-26-2021

(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?


RE: What can the event.widget reference be used for? - Yoriz - Aug-26-2021

Refer to tkinter widget by its instance


RE: What can the event.widget reference be used for? - Knickers - Aug-26-2021

(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!