Let’s say that I have the following code:
root = Tk()
open = Button(self.root, text='Open', command=self.open, state='disabled')
open.pack()
close = Button(self.root, text='Close', command=self.close, state='disabled')
close.pack()
I only want to enable the buttons when some action is performed, so I need to access the buttons again later to edit the state variable. Rather than adding the buttons to a separate list and storing that, is there a way of accessing the buttons, or, for that matter, any set of objects that I have attached to the root (Menus, Drop down lists, or whatever), by calling a method on the root?
There is no definitive way to ask the root window for a list of all widgets. You can use
pack_slavesorgrid_slavesto get a list of widgets managed by a particular container, but depending on how you write your app that’s no guarantee you’ll get all the widgets.You can also use
winfo_childrento get a list of all direct descendants of a widget. If you have a nested hierarchy of widgets (for example, by using frames as intermediary containers for organizational purpose) you may have to do some sort of looping to find a particular widget.The best and simplest approach is to have your application be an instance of a class. You can then save references to the widgets as attributes of the class. I highly recommend this approach, there’s simply no good reason to do it any other way.
For example: