Search code examples
pythontkintertreeview

How to get the first heading in the treeview Tkinter Python


I have written this code:

def fee_foo():
    fee_screen = tk.Tk()
    fee_screen.title("Fee Information")
    fee_screen.geometry("500x500")
  # Execute the SELECT statement and retrieve the results
    # Execute the SELECT statement and retrieve the results
    query = "SELECT roll_no, paid, due_date, amount FROM fee"
    cursor.execute(query)
    results = cursor.fetchall()

    # Create the Treeview widget
    treeview = ttk.Treeview(fee_screen)
    treeview.pack(fill=tk.BOTH, expand=True)

    # Configure the columns of the Treeview widget
    treeview["columns"] = ("roll_no","paid", "due_date", "amount")
    treeview.column("roll_no",width=100)
    treeview.column("paid", width=100)
    treeview.column("due_date", width=100)
    treeview.column("amount", width=100)

    # Set the column headers of the Treeview widget
    treeview.heading("roll_no",text="Roll No")
    treeview.heading("paid", text="Paid")
    treeview.heading("due_date", text="Due Date")
    treeview.heading("amount", text="Amount")
    # Insert the rows into the Treeview widget
    for result in results:
        treeview.insert("", tk.END, text=result[0], values=result[1:])

but the results I am getting are something like this: enter image description here Can you kindly tell me whats wrong with my code?

I tried changing the values of the columns and heading variables and re-indexing the tuple in the treeview.insert line.


Solution

  • I found the answer if we modify the column arrangements like this:

    # Configure the columns of the Treeview widget
        treeview["columns"] = ("paid", "due_date", "amount")
        treeview.column("paid", width=100)
        treeview.column("due_date", width=100)
        treeview.column("amount", width=100)
    
        # Set the column headers of the Treeview widget
        treeview.heading("#0", text="Roll No")
        treeview.heading("paid", text="Paid")
        treeview.heading("due_date", text="Due Date")
        treeview.heading("amount", text="Amount")
    
        # Insert the rows into the Treeview widget
        for result in results:
            treeview.insert("", tk.END, text=result[0], values=result[1:])
    

    it displays the correct arrangement of columns