在wxTreeCtrl中查找某个子节点并在wxPython中更新TreeCtrl

时间:2011-10-27 17:36:16

标签: python wxpython

如何检查wx.TreeCtrl对象中的某个根是否有某个孩子?

每次用户添加子项时,我都在编写手动函数来更新TreeCtrl。有没有办法自动化这个?

3 个答案:

答案 0 :(得分:1)

您可能需要考虑将数据存储在其他一些易于搜索的结构中,并使用TreeCtrl来显示它。否则,您可以迭代TreeCtrl根项目的子项,如下所示:

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())

取消注释注释行将使其成为递归搜索。

答案 1 :(得分:0)

处理递归树遍历的一种更好的方法是将它包装在生成器对象中,然后您可以重新使用它来在树节点上执行您喜欢的任何操作:

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

答案 2 :(得分:0)

按文字搜索而不递归:

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