簡體   English   中英

在wxTreeCtrl中查找某些子級並在wxPython中更新TreeCtrl

[英]Finding certain child in wxTreeCtrl and updating TreeCtrl in wxPython

如何檢查wx.TreeCtrl對象中的某個根是否具有某個子級?

我正在編寫手動函數來每次用戶添加一個孩子時更新TreeCtrl。是否有一種自動的方法?

您可能要考慮將數據存儲在其他易於搜索的結構中,並僅使用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())

取消注釋注釋行將使其成為遞歸搜索。

處理遞歸樹遍歷的一種更好的方法是將其包裝在一個生成器對象中,然后可以再次使用該對象來對樹節點執行任何您喜歡的操作:

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

對於沒有遞歸的文本搜索:

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