This is some code @JonB did for me a long time ago. Well i mean helped me with from a post.
But if you are working with ui's , it can be useful to easily get each subview regardless of its nesting.
His class can either do depth or breath.
As I say, this is more or less a re-post
# from @JonB
import ui
from collections import deque
class ViewWalker(object):
'''simple iterator for ui.View objects, capable of depth or breadth first traversal'''
def __init__(self,v,breadthfirst=False):
self._dq=deque([v])
self._breadth=breadthfirst
def __iter__(self):
'''required for iterator objects'''
return self
def __next__(self):
'''required for iterator objects. raise stopiteration once the queue is empty. '''
if not self._dq:
raise StopIteration
#pop next view...
if self._breadth:
v=self._dq.popleft()# oldest entry (FIFO)
else:
v=self._dq.pop() # newest entry (stack)
#then push its subviews
if hasattr(v,'subviews'):
self._dq.extend(v.subviews)
return v
class MyClass(ui.View):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.make_view()
def make_view(self):
# just add some btns to the view as a test
for i in range(1, 11):
btn = ui.Button(name = 'btn{}'.format(i))
self.add_subview(btn)
lb = ui.Label(name = 'lbl{}'.format(i))
btn.add_subview(lb)
mc = MyClass(name = 'CustomView')
print('depthfirst:', [s.name for s in ViewWalker(mc)])
print('\n')
print ('breadthfirst:', [s.name for s in ViewWalker(mc,True )])