Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to search widget by name in Tkinter?

Tags:

python

tkinter

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?

like image 718
grigoryvp Avatar asked Jan 17 '12 12:01

grigoryvp


2 Answers

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>
 
like image 128
jsbueno Avatar answered Oct 13 '22 12:10

jsbueno


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'] # ...
like image 21
tzot Avatar answered Oct 13 '22 13:10

tzot