Wxpython: TreeCtrl: Iteration over a tree

python, wxpython

Solution

You could use a function that is inside this one (in its namespace only) that will check if it matches the conditiin or not. If it does return the item if it doesn't, continue.

Otherwise you could check your condition just after the `while` line. This way the `item` variable will be defined by the first child before the loop and evaluated like any other.

Still another way: (or a mix of the two)

(child, cookie) = self.GetFirstChild(item)
while child.IsOk():
    do_something(child)
     (child, cookie) = self.GetNextChild(item, cookie)

Problem

I am using the following method to iterate over all the nodes of a wxpython treectrl. ``` def get_desired_parent(self, name, selectednode = None): if selectednode == None: selectednode = self.treeCtrl.RootItem # First perform the action on the first object separately childcount = self.treeCtrl.GetChildrenCount(selectednode, False) if childcount == 0: return None (item,cookie) = self.treeCtrl.GetFirstChild(selectednode) if self.treeCtrl.GetItemText(item) == name: return item while childcount > 1: childcount = childcount - 1 # Then iterate over the rest of objects (item,cookie) = self.treeCtrl.GetNextChild(item,cookie) if self.treeCtrl.GetItemText(item) == name: return item return None ``` This problem of excess code becomes even more apparent when I am iterating inside the structure recursively. Is there another way of performing the same actions in more compact manner, to make my code more concise / pythonic.

Original source