Finding certain child in wxTreeCtrl and updating TreeCtrl in wxPython

六眼飞鱼酱① 提交于 2021-02-11 15:15:50

问题


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?


回答1:


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.




回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/7919992/finding-certain-child-in-wxtreectrl-and-updating-treectrl-in-wxpython

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!