Home > Enterprise >  TreeView header text update with each new SQL query
TreeView header text update with each new SQL query

Time:01-24

I am required to build a very simple database app where I can run MySQL queries and show them on the screen. I am using tkinter TreeView for this purpose;

root = Tk()
root.title("Database Access")
root.geometry("1280x720")
mycursor = db.cursor()

input1 = Entry(root, width=100)
input1.pack()

columns1 = ['111', '222', '333', '444', '555', '666', '777', '888']
tree = ttk.Treeview(root, columns=columns1, show='headings')

tree.heading('#1', text=columns1[0])
tree.heading('#2', text=columns1[1])
tree.heading('#3', text=columns1[2])
tree.heading('#4', text=columns1[3])
tree.heading('#5', text=columns1[4])
tree.heading('#6', text=columns1[5])
tree.heading('#7', text=columns1[6])
tree.heading('#8', text=columns1[7])

tree.pack(expand=True)

And I defined a submit button so whenever the user writes a query, the resulting table can be shown in treeview;


def submit():
    mycursor.execute(input1.get())
    result = mycursor.fetchall()

    first_data = map(lambda x: x[0], mycursor.description)
    columns1.clear()
    for i in first_data:
        columns1.append(i)
        # stuck here ===============
    root.update()
    print(columns1) # it prints the correct new values but now shown in headers
        
    for row in result:
        tree.insert('', 'end', values=row[0:8])

buttonSubmit = Button(root, text="SUBMIT QUERY", width=50, command=submit)
buttonSubmit.pack()

The problem is I can't get the column headers in the window to updated.

If I even re-configure tree headings right after #stuck here# like exactly as before;

tree.heading('#1', text=columns1[0])
tree.heading('#2', text=columns1[1])
tree.heading('#3', text=columns1[2])
tree.heading('#4', text=columns1[3])
tree.heading('#5', text=columns1[4])
tree.heading('#6', text=columns1[5])
tree.heading('#7', text=columns1[6])
tree.heading('#8', text=columns1[7])

It begins to write the new headers but crashes when it fails to find a value in the corresponding column as expected because not all query results are exactly 8 columns long.

IndexError: list index out of range

After a long search I couldn't figure out how to hold a placeholder in the tree headings in a healthy convenient way so I can pass new header names easily.

Hope it is clear. I'm new to programming but other simple approaches are also welcome.

CodePudding user response:

You need to update columns option of tree and the headings inside submit(). Also you can simply use mycursor.column_names:

def submit():
    mycursor.execute(input1.get())
    result = mycursor.fetchall()

    tree.config(columns=mycursor.column_names)
    for col in mycursor.column_names:
        tree.heading(col, text=col)

    for row in result:
        tree.insert('', 'end', values=row)
  •  Tags:  
  • Related