Search code examples
pythontkintertreeview

In my treeview (python tkinter), when I add data, I want the data to be added based on parent name (tkinter)


In my TreeView I enter values manually, I would like to have them displayed like this:

Parent name1

child 1 

child 2 
   
child 3 

parent name 2 

child 1 

child 2 

The data that I enter should be added as a child to the respective parent every time I enter (the entered parent name should be checked with pre-existing parent names in treeview). Note: The data is entered into TreeView only if the failure rate is a numeric value.

#treeview
my_tree = ttk.Treeview(tree_frame,height= 15, yscrollcommand=tree_scroll.set)
my_tree.pack()

tree_scroll.config(command=my_tree.yview)

my_tree['columns'] = ("fun"," rate", "cv", "id")

my_tree.column("#0",width=100)
my_tree.column("fun",anchor=W,width=100)
my_tree.column("rate",anchor=W,width=100)
my_tree.column("cv",anchor=W,width=120)
my_tree.column("id",anchor=W,width=120)

my_tree.heading("#0",text='name',anchor=W)
my_tree.heading("fun", text='Fun', anchor=W)
my_tree.heading("rate",text='rate',anchor=W)
my_tree.heading("cv", text='Cv',anchor=W)
my_tree.heading("id",text='id',anchor=W)

main.mainloop()

Solution

  • First all ieX are None because it is the result of .grid(...). You need to split the line like:

    ie1 = Entry(input_frame, width = 50).grid(row=0, column=1,padx=5,pady=5)
    

    into two lines:

    ie1 = Entry(input_frame, width = 50)
    ie1.grid(row=0, column=1,padx=5,pady=5)
    

    Then you need to modify add() to insert parent and child separately:

    def add():
        global count
        a = ie3.get()
        try:
            float(a)
            component = ie1.get()
            if not my_tree.exists(component):
                # insert parent
                my_tree.insert(parent="", index="end", iid=component, text=component)
            # insert child
            my_tree.insert(parent=component, index='end', iid=count, values=(ie2.get(),ie3.get(),ie4.get(),ie5.get()))                                                                                         
            count += 1
        except ValueError:
            mesg()