Search code examples
pythonuser-interfacetkintertreeviewttk

Merge nodes in tkinter treeview


How can one merge two nodes in a tkinter treeview widget?

Suppose you have this simple structure in your treeview:

-Parent1
   -Child1
-Parent2
   -Child2

And you want to merge the two parent items to create the following structure:

-Parent1
   -Child1
   -Child2

The iid's of the parent nodes are known. Basically it is a transfer of the children nodes to one parent to the other and a deletion of the parent left without children. Is there a way implemented in tkinter to do so or do you have to define something yourself?

Sample code creating the basic example:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

tree = ttk.Treeview(
    root,
    selectmode='browse'
)
tree.insert('', 0, iid=1, text='Parent1')
tree.insert('', 0, iid=2, text='Parent2')

tree.insert(1, 0, text='Child 1')
tree.insert(2, 0, text='Child 2')

tree.pack()
root.mainloop()

Solution

  • You can use tree.move() to move 'Child 2' to 'Parent 1':

    tree.move(child2, 1, 'end')
    

    where child2 is the iid of 'Child 2':

    child2 = tree.insert(2, 0, text='Child 2')
    

    Then delete 'Parent 2':

    tree.delete(2)