Home > OS >  Python - tkinter: Illustration of tree in treeview
Python - tkinter: Illustration of tree in treeview

Time:03-28

Is their a way to illustrate some tree like:

from anytree import Node, RenderTree

udo = Node("Udo")
marc = Node("Marc", parent=udo)
lian = Node("Lian", parent=marc)
dan = Node("Dan", parent=udo)
jet = Node("Jet", parent=dan)
jan = Node("Jan", parent=dan)
joe = Node("Joe", parent=dan)

in tkinter as treeview of form:

[ ]Udo
 ├──[ ] Marc
 │   └──[ ] Lian
 └── [ ]Dan
      ├──[ ] Jet
      ├──[ ] Jan
      └──[ ] Joe

with the property that a click on [ ] opens the subtree of the node right to the button itself. The following illustration shows probably what kind treeview I have in mind:

example of treeview

CodePudding user response:

Found some way, but dont't know if their is some better method to solve the problem.

Code:

from anytree import Node, RenderTree, AsciiStyle, PreOrderIter
from tkinter import *
from tkinter import ttk


udo = Node("Udo")
marc = Node("Marc", parent=udo)
lian = Node("Lian", parent=marc)
dan = Node("Dan", parent=udo)
jet = Node("Jet", parent=dan)
jan = Node("Jan", parent=dan)
joe = Node("Joe", parent=dan)



class TreeView(Frame):
    def __init__(self, parent, tree):
        self.tree = tree
        self.treeview = ttk.Treeview(parent, height = 7)

    def generate(self):
        self.treeview.pack()

        index = 0

        for node in PreOrderIter(self.tree):
            self.treeview.insert('',f'{index}', node.name, text = node.name)
            index = index   1

        for node in PreOrderIter(self.tree):
            for child in node.children:
                self.treeview.move(child.name, node.name, 'end')


root = Tk()

tv = TreeView(root, udo)
tv.generate()

root.mainloop()

Output:

enter image description here

  • Related