Looping over widgets in Tkinter Looping over widgets in Tkinter tkinter tkinter

Looping over widgets in Tkinter


Your consistant name scheme let you use the variable name to iterate through your variables:

for i in range(1,n):    label = getattr(self, "lab"+str(i))

You may also consider relying on Tkinter whom retain a tree structure of your widgets accessible through children widget attribute (a dictionary):

for child in frame.children.values():    #do something to all children

And eventually add some filtering if your frame contains other widgets. For instance, to filter on classes of widgets:

for label in filter(lambda w:isinstance(w,Label), frame.children.itervalues()):    #do something on labels

Note that children does not have any guarantee on order traversal. For such service, you may rely on geometry manager infos, ie pack_slaves or grid_slaves:

for child in frame.pack_slaves():    #traverse in pack addition order#orfor child in reversed(frame.grid_slaves()):    #traverse in grid addition order


The easiest way is to store references to each widget in a list or dictionary rather than (or in addition to) scaler instance variables.