简体   繁体   中英

Finding certain child in wxTreeCtrl and updating TreeCtrl in wxPython

How can I check if a certain root in a wx.TreeCtrl object has a certain child or not?

I am writing manual functions to update TreeCtrl every time a child is added by user.Is there a way to automate this?

You might want to consider storing the data in some other easily-searchable structure, and using the TreeCtrl just to display it. Otherwise, you can iterate over the children of a TreeCtrl root item like this:

def item_exists(tree, match, root):
    item, cookie = tree.GetFirstChild(root)

    while item.IsOk():
        if tree.GetItemText(item) == match:
            return True
        #if tree.ItemHasChildren(item):
        #    if item_exists(tree, match, item):
        #        return True
        item, cookie = tree.GetNextChild(root, cookie)
    return False

result = item_exists(tree, 'some text', tree.GetRootItem())

Uncommenting the commented lines will make it a recursive search.

A nicer way to handle recursive tree traversal is to wrap it in a generator object, which you can then re-use to perform any operation you like on your tree nodes:

def walk_branches(tree,root):
    """ a generator that recursively yields child nodes of a wx.TreeCtrl """
    item, cookie = tree.GetFirstChild(root)
    while item.IsOk():
        yield item
        if tree.ItemHasChildren(item):
            walk_branches(tree,item)
        item,cookie = tree.GetNextChild(root,cookie)

for node in walk_branches(my_tree,my_root):
    # do stuff

For searching by text without recursion :

def GetItemByText(self, search_text, tree_ctrl_instance):
        retval = None
        root_list = [tree_ctrl_instance.GetRootItem()]
        for root_child in root_list:
            item, cookie = tree_ctrl_instance.GetFirstChild(root_child)
            while item.IsOk():
                if tree_ctrl_instance.GetItemText(item) == search_text:
                    retval = item
                    break
                if tree_ctrl_instance.ItemHasChildren(item):
                    root_list.append(item)
                item, cookie = tree_ctrl_instance.GetNextChild(root_child, cookie)
        return retval

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM