2016-04-03 370 views
2

我已經使用treeview創建了一個表,並且我想插入從mysql table中提取的數據如果任何人都可以幫助我,因爲我嘗試了所有級別最好的但仍然是徒勞的。這個聲明tree.insert("", 1, text=2, values=("name", "5", "5"))可以插入井數據,但不是從數據庫中,但我想從數據庫中獲取並顯示它。 這裏是我嘗試過的代碼,但它失敗了。請幫助。 '我怎樣才能顯示數據在Tkinter treeview從Mysql表使用python取得

from Tkinter import * 
import ttk 
import MySQLdb 

root = Tk() 
root.geometry("320x240") 

tree = ttk.Treeview(root) 

conn = MySQLdb.connect("localhost", "root", "drake", "OSCAR") 
cursor = conn.cursor() 

tree["columns"] = ("one", "two", "three") 
tree.column("one", width=100) 
tree.column("two", width=100) 
tree.column("three", width=100) 

tree.heading("#0", text='ID', anchor='w') 
tree.column("#0", anchor="w") 
tree.heading("one", text="NAME") 
tree.heading("two", text="VOTES") 
tree.heading("three", text="PERSENTAGE") 

for i in range(1, 6): 
    cursor.execute("""select name from president where ID =%s""", (i,)) 
    nm = cursor.fetchone()[0] 
    cursor.execute("""select votes from president where ID =%s""", (i,)) 
    vot = cursor.fetchone()[0] 
    cursor.execute("""select percentage from president where ID =%s""",(i,)) 
    percent = cursor.fetchone()[0] 

    tree.insert("", i, text=i, values=(nm, vot, percent)), 

tree.pack() 
root.mainloop() 

`

回答

1

要解決你的問題,首先你需要在使用該查詢讀取數據庫中的所有行:

SELECT * FROM president 

這您需要執行:

cursor.execute("""SELECT * FROM president""") 

現在,簡單地遍歷所有的行並插入一個個tree

UPDATE:

我想你的表結構是這樣的:

ID | name | votes | percentage 

所以,你可以運行這個命令:

cpt = 0 # Counter representing the ID of your code. 
for row in cursor: 
    # I suppose the first column of your table is ID 
    tree.insert('', 'end', text=str(cpt), values=(row[1], row[2], row[3])) 
    cpt += 1 # increment the ID 
+0

你好@比爾,我收到一個類型錯誤: '光標' 對象而不是callable.its從光標'(名稱,投票,百分比):' –

+0

檢查我的編輯。告訴我,如果你的桌子的結構是我提到的@ByamukamaOscar –

+0

是的,它是這樣的,我要去試試看。感謝你付出的努力@bill –

1

IV使用的sqlite3不MySQL,但我假設是從SQL返回的值被放入一個多維陣列中,這些都是陣列,其需要一個以上的指數例如

array[0][1] 

下面的代碼是用於修改樹

for i in self.tree.get_children(): 
    self.tree.delete(i) #clears current values from tree 

for student in StudentList: 
    self.tree.insert("" , 0,values=(student[0],student[1]) 
    #the index used would depend on what you want to be put into the tree 
    #only uses one index per value instead of two as the for loop changes the first index 

注意,這是從我的課程(訂票系統)複製,因此名稱中使用