Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从嵌套字典创建tkinter嵌套树视图_Python_Recursion_Tkinter_Nested_Treeview - Fatal编程技术网

Python 从嵌套字典创建tkinter嵌套树视图

Python 从嵌套字典创建tkinter嵌套树视图,python,recursion,tkinter,nested,treeview,Python,Recursion,Tkinter,Nested,Treeview,我有一个这样的嵌套字典,我想用它来填充分层树视图 hierarchy = { 'a': { 'b': { 'e': 'DATA', 'f': 'DATA', 'g': { 'h': 'DATA',

我有一个这样的嵌套字典,我想用它来填充分层树视图

hierarchy = {
                'a': {
                    'b': {
                        'e': 'DATA',
                        'f': 'DATA',
                        'g': {
                            'h': 'DATA',
                            'i': 'DATA',
                            'j': 'DATA'
                        },
                        'm': {
                            'n': 'DATA',
                            'o': 'DATA',
                            'p': 'DATA'
                        }
                    },
                    'c': 'DATA',
                    'd': 'DATA'
                }
            }
代码应该遍历嵌套字典并创建适当的tk treeview节点。基本上是复制PyCharm的视图,该视图允许您打开一个嵌套字典,并尽可能深入

我正在粘贴我在下面写的代码,但是递归根本不起作用。我粘贴它只是为了方便,不必重新创建tk窗口等

root = tk.Tk()
root.geometry("900x900")
tree = ttk.Treeview(root)
ttk.Style().configure('Treeview', rowheight=30)
tree["columns"] = ("one", "two", 'three')
tree.column("one", width=100)
tree.column("two", width=100)
tree.heading("one", text="a")
tree.heading("two", text="b")
tree.heading("three", text="c")

nodes = {}

def add_node(elem):
    for i, j in elem.items():
        if isinstance(j, dict):
            add_node(j)
        else:
            if i in nodes.keys():
                nodes[j] = tree.insert(i, 1, j, text=j)
            else:
                nodes[i] = tree.insert("", 1, i, text=i)

for k, v in hierarchy.items():
    add_node(k)

tree.pack(expand=True, fill='both')
root.mainloop()
root.destroy()
我想出来了:

root = tk.Tk()
root.geometry("900x900")
tree = ttk.Treeview(root)
ttk.Style().configure('Treeview', rowheight=30)
tree["columns"] = ("one", "two", 'three')
tree.column("one", width=100)
tree.column("two", width=100)
tree.heading("one", text="a")
tree.heading("two", text="b")
tree.heading("three", text="c")

def add_node(k, v):
    for i, j in v.items():
        tree.insert(k, 1, i, text=i)
        if isinstance(j, dict):
            add_node(i, j)

for k, v in hierarchy.items():
    tree.insert("", 1, k, text=k)
    add_node(k, v)

tree.pack(expand=True, fill='both')
root.mainloop()

无关:在节点中使用
i
而不是-O(1)而不是带有
keys()
的O(n)。这很奇怪,但谢谢你,我不知道这一点。