我需要構建一個非常簡單的資料庫應用程式,我可以在其中運行 MySQL 查詢并將它們顯示在螢屏上。我TreeView為此目的使用 tkinter;
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)
我定義了一個提交按鈕,所以每當用戶撰寫查詢時,結果表都可以顯示在樹視圖中;
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()
問題是我無法更新視窗中的列標題。
如果我什至像以前一樣在#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])
它開始寫入新的標頭,但在未能按預期在相應列中找到值時崩潰,因為并非所有查詢結果都恰好是 8 列長。
IndexError: list index out of range
經過長時間的搜索,我無法弄清楚如何以一種健康便捷的方式在樹標題中保留占位符,以便我可以輕松地傳遞新的標題名稱。
希望很清楚。我是編程新手,但也歡迎使用其他簡單的方法。
uj5u.com熱心網友回復:
您需要更新columns選項tree和里面的標題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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/419726.html
標籤:
上一篇:多對多關系中的SQL查詢
