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?

grigoryvp
  • 40,413
  • 64
  • 174
  • 277

2 Answers2

15

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>
 
nixalott
  • 15
  • 5
jsbueno
  • 99,910
  • 10
  • 151
  • 209
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'] # ...
tzot
  • 92,761
  • 29
  • 141
  • 204
  • 3
    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. – josch Jun 12 '19 at 21:02