【问题标题】:how can i display data in Tkinter treeview fetched from Mysql table using python如何在 Tkinter 树视图中显示使用 python 从 Mysql 表中获取的数据
【发布时间】:2016-07-22 22:25:37
【问题描述】:

我已经使用树视图创建了一个表,我想插入从 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()

`

【问题讨论】:

    标签: python mysql tkinter treeview


    【解决方案1】:

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

    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
    

    【讨论】:

    • hello@Bill,我收到一个 Typeerror: 'cursor' object is not callable.its from the for (name,votes,percentage) in cursor:
    • 检查我的编辑。告诉我你的桌子结构是否像我提到的那样@ByamukamaOscar
    • 是的,就是这样,我会尝试看看。谢谢你付出的努力@bill
    • 如果您对此代码还有其他问题,请随时询问
    • 为什么ttk.Scrollbar 在从数据库中获取数据时不起作用。它在将数据直接插入tree 时工作
    【解决方案2】:

    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
    

    请注意,这是从我的课程作业(预订系统)中复制的,因此使用的名称

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-17
      • 2014-06-01
      相关资源
      最近更新 更多