python如何将监听到数据利用tkinter显示_如何使用python从Mysql表获取的Tkinter treeview中显示数据...

1586010002-jmsa.png

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

which you need to execute:

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

Now, simply loop over the rows and insert them one by one in tree:

UPDATE:

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值