[Python] Hierarchical treeview from mysql data

Discussão em 'Python' iniciado por Stack, Maio 6, 2025.

  1. Stack

    Stack Membro Participativo

    I need help to build a hierarchical treeview taking data from a mysql table with these columns: ID, ID_parent, Description. I managed to fill only the first level list and I need to create a function that calls the children and their children. Can you help me? Thanks.

    import tkinter as tk
    from tkinter import *
    from tkinter import ttk
    import mysql.connector
    from tkinter.font import nametofont

    def add_child(id_parent):
    fill treeview next level
    add_child(id_parent)


    root = tk.Tk()
    root.resizable(False,False)
    root.configure(bg="#595252")
    root.title("Treeview")
    style=ttk.Style()
    style.theme_use('default')
    style.configure("Treeview",
    background="#D3D3D3",
    foreground="black",
    rowheight=34,
    fieldbackground="#D3D3D3",font=['Calibri',12,'normal'])
    tree_frame=Frame(root)
    tree_frame.pack(padx=10,pady=5)
    tree_scroll=Scrollbar(tree_frame)
    tree_scroll.pack(side=RIGHT,fill=Y)
    my_tree=ttk.Treeview(tree_frame,yscrollcommand=tree_scroll.set,selectmode='extended', height=12)
    my_tree.pack(fill="both",expand=True)
    tree_scroll.config(command=my_tree.yview)
    my_tree.column("#0", width=500, stretch=NO )
    my_tree.heading("#0",text="ID", anchor=W)
    style.map('Treeview', background=[('selected',"#347083")])
    nametofont("TkHeadingFont").configure(size=12)
    icon = ImageTk.PhotoImage(Image.open("I:/Progetti/Image/VerdeS2.ico"))

    node = my_tree.insert("", "end", "H1", text="H1")

    conn = mysql.connector.connect(user='root', password='', host='localhost', database='employees')
    c = conn.cursor()
    c.execute("SELECT ID, ID_PARENT, DESCRIPTION FROM employees WHERE ID_PARENT='H1' GROUP BY ID_PARENT, ID ORDER BY ID_PARENT, ID")
    rows = c.fetchall()
    count=0
    for record in rows:
    my_tree.insert(parent="H1",index='end',iid=count,text=record[0] + ' - ' + record[2], image=icon, values=(record[0],record[2]))
    count += 1
    add_child(id_parent)

    conn.close()

    add_child_button = tk.Button(root, text="Add Child Item", command=add_child_item)
    add_child_button.pack()

    add_sibling_button = tk.Button(root, text="Add Sibling Item", command=add_sibling_item)
    add_sibling_button.pack()

    delete_button = tk.Button(root, text="Delete Item", command=delete_item)
    delete_button.pack()

    root.mainloop()


    I can't define the recursive function to insert children

    Continue reading...

Compartilhe esta Página