简体   繁体   English

在wxTreeCtrl中查找某些子级并在wxPython中更新TreeCtrl

[英]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? 如何检查wx.TreeCtrl对象中的某个根是否具有某个子级?

I am writing manual functions to update TreeCtrl every time a child is added by user.Is there a way to automate this? 我正在编写手动函数来每次用户添加一个孩子时更新TreeCtrl。是否有一种自动的方法?

You might want to consider storing the data in some other easily-searchable structure, and using the TreeCtrl just to display it. 您可能要考虑将数据存储在其他易于搜索的结构中,并仅使用TreeCtrl来显示它。 Otherwise, you can iterate over the children of a TreeCtrl root item like this: 否则,您可以像这样遍历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())

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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