TreeView header 文本随每个新 SQL 查询更新

TreeView header text update with each new SQL query

我需要构建一个非常简单的数据库应用程序,我可以在其中 运行 MySQL 查询并将它们显示在屏幕上。为此,我正在使用 tkinter TreeView

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)

并且我定义了一个提交按钮,因此每当用户编写查询时,结果 table 可以显示在树视图中;


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()

问题是我无法更新 window 中的列 headers。

如果我什至 re-configure 树标题在#stuck here# 之后就像以前一样;

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])

它开始写入新的 headers 但当它未能按预期在相应列中找到值时崩溃,因为并非所有查询结果都恰好是 8 列长。

IndexError: list index out of range

经过长时间的搜索,我无法弄清楚如何以健康方便的方式在树标题中保留占位符,以便我可以轻松传递新的 header 名称。

希望清楚。我是编程新手,但也欢迎使用其他简单的方法。

您需要更新 treecolumns 选项和 submit() 中的标题。您也可以简单地使用 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)