9

If i create a widget in Tkinter i can specify a widget name that takes part in tcl/tk "widget path" concept. For example:

from Tkinter import *
button = Button( Frame( Tk(), name = "myframe" ), name = "mybutton" )
str( button ) == ".myframe.mybutton"

Is it possible to get a widget by it's name, "mybutton" in my example?

2 Answers 2

16

Yes, but you have to hold a reference to the root Tk instance: just use the Tk.nametowidget() method:

>>> from Tkinter import *
>>> win = Tk()
>>> button = Button( Frame( win, name = "myframe" ), name = "mybutton" )
>>> win.nametowidget("myframe.mybutton")
<Tkinter.Button instance at 0x2550c68>
 
Sign up to request clarification or add additional context in comments.

Comments

8

Every Tkinter widget has an attribute children which is a dictionary of widget namewidget instance. Given that, one can find any subwidget by:

widget.children['subwidget_name'].children['subsubwidget_name'] # ...

1 Comment

Instead of using widget.children['foo'] you could use widget.nametowidget('foo') to not rely on the attribute dict. nametowidget is internally query-ing that attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.