8

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
  • 37,371
  • 60
  • 164
  • 268

2 Answers2

13

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
  • 86,446
  • 9
  • 131
  • 182
7

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
  • 87,612
  • 28
  • 135
  • 198
  • 2
    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