【问题标题】:Finding certain child in wxTreeCtrl and updating TreeCtrl in wxPython在 wxTreeCtrl 中查找某个子项并在 wxPython 中更新 TreeCtrl
【发布时间】:2019-08-29 19:11:46
【问题描述】:

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

每次用户添加孩子时,我都会编写手动函数来更新 TreeCtrl。有没有办法自动执行此操作?

【问题讨论】:

    标签: python wxpython


    【解决方案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())
    

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

    【讨论】:

      【解决方案2】:

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

      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】:

        用于不递归的文本搜索:

        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
        

        【讨论】:

        • 这似乎对我不起作用。 root_list = [tree_ctrl_instance.GetRootItem()] 这应该返回树中所有项目的列表吗?
        猜你喜欢
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 2017-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多