如何使用python从Mysql表获取的Tkinter treeview中显示数据 [英] how can i display data in Tkinter treeview fetched from Mysql table using python
问题描述
am已经使用treeview创建了一个表,我想插入从mysql table中获取的数据.如果有人可以帮助我,因为我尽了最大的努力但仍然徒劳.使用此语句tree.insert("", 1, text=2, values=("name", "5", "5"))
可以插入好数据,但不是从数据库,但我想从数据库中获取并显示它.
这是我尝试过的代码,但是失败了.请帮助.
`
am have created a table using treeview and i would like to insert in data fetched from mysql table.if any one can help me because i have tried all my level best but still in vain.with this statement tree.insert("", 1, text=2, values=("name", "5", "5"))
can insert well data but not from the database, but i would like to fetch from the database and display it.
here is the code i have tried but it has failed.please help.
`
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()
`
推荐答案
要解决您的问题,首先,您需要使用以下查询读取数据库的所有行:
To resolve your problem, first you will need to read all the rows of the database using this query:
SELECT * FROM president
您需要执行的操作
cursor.execute("""SELECT * FROM president""")
现在,只需循环遍历行,然后将它们一一插入tree
:
Now, simply loop over the rows and insert them one by one in tree
:
更新:
我想你的表结构是这样的:
I suppose your table structure is like this:
ID | name | votes | percentage
因此您可以运行以下代码:
So you could run this:
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
这篇关于如何使用python从Mysql表获取的Tkinter treeview中显示数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!