Jozef Méry
Jozef Méry

Reputation: 357

How to get object name of the widget in focus?

Very similiar to

print("focus object class:", window2.focus_get().__class__) 

taken from here: Python get focused entry name , but I need the exact name of the object. Something like: self.entrywidget_1

OR:

What to fill the place holder to make if true ?

print(self.focus_get().__class__)
if self.focus_get().__class__ == "placeholder":
    print("I work")

The first print returns < class 'tkinter.Entry' >

Upvotes: 2

Views: 3302

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385840

You can't. Any given object can have many names. For example, given the following code, which name would you expect to get?

self.foo = tk.Button(...)
self.bar = self.foo

You rarely, if ever, need the name of the widget. Having a reference to the widget -- like that is returned by focus_get() -- is all you need. With that yo can insert data, delete data, destroy the widget, get the widget contents, etc.

If you really do need some predictable, unique identifier in the case where the same function must work for multiple widgets, you can give each widget a custom attribute that is a symbolic name. You can then get that name at runtime. For example:

e = tk.Entry(...)
e.name = "placeholder"
...
focused_widget = root.focus_get()
print (the name of the focused widget is %s" % focused_widget.name)

Again, you likely won't ever need that. For example, if you want to delete the text in the focused widget, just use the reference to the widget:

focused_widget.delete(0, "end")

If all you really need is to check if the focused widget is a specific widget, just do a direct comparison:

...
self.placeholder = tk.Entry(...)
...
def whatever(self):
    focused_widget = root.focus_get()
    if focused_widget == self.placeholder:
        print("I work")

Upvotes: 5

Related Questions