gpt4 book ai didi

python - 我如何在使用python从Mysql表中获取的Tkinter treeview中显示数据

转载 作者:行者123 更新时间:2023-11-29 02:17:59 25 4
gpt4 key购买 nike

我已经使用 treeview 创建了一个表,我想插入从 mysql 表中获取的数据。如果有人可以帮助我,因为我已经尽我所能,但仍然是徒劳的。使用此语句 tree。 insert("", 1, text=2, values=("name", "5", "5")) 可以插入数据但不能从数据库中插入,但我想从数据库中获取并显示它。这是我试过但失败的代码。请帮忙。`

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

`

最佳答案

要解决您的问题,首先您需要使用此查询读取数据库的所有行:

SELECT * FROM president

你需要执行的:

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

现在,只需遍历行并将它们一一插入到 tree 中:

更新:

我想你的表结构是这样的:

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

关于python - 我如何在使用python从Mysql表中获取的Tkinter treeview中显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36384692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com