简体   繁体   English

python数据库(sqlite3)和treeview

[英]python database (sqlite3) and the treeview

hi everyone i have a problem in my code i try to display my tables from the data base on the treeview but i can't i see this error "TypeError: 'sqlite3.Cursor' object is not subscriptable" might be because i have three table on my data base these is a part of my code : 嗨,大家好,我的代码有问题,我尝试在树状视图上从数据库中显示表,但我看不到此错误“ TypeError:'sqlite3.Cursor'对象不可下标”,可能是因为我有三个我数据库上的表,这是我的代码的一部分:

tv=ttk.Treeview(root)
tv.place(x=24,y=335)
style = ttk.Style(root)
style.configure('Treeview', rowheight=30)
tv.heading('#0',text="ID")
tv.column("#0",width=99)
tv.configure(column=('#Type','#Code','#Designation','#Prix achat'))
tv.heading('#Type',text="Type")
tv.heading('#Code',text="Code")
tv.heading('#Designation',text="Designation")
tv.heading('#Prix achat',text="Prix achat (DZA)")

cur=issam.tree_select()
for i in cur:
    tv.insert('','end','#{}'.format(i['ID']),text=i['ID'])
    tv.set('#{}'.format(i['ID']),'#Type',i['type'])
    tv.set('#{}'.format(i['ID']),'#Code',i['Code'])
    tv.set('#{}'.format(i['ID']),'#Designation',i['Designation'])
    tv.set('#{}'.format(i['ID']),'#Prix achat',i['pa'])

and these is the function in database file (in a class): 这些是数据库文件中的函数(在一个类中):

def tree_select(self):
    cursor=self.db.execute('SELECT * FROM poisson ')
    cur2=self.db.execute('SELECT * FROM plant')
    cur3=self.db.execute('SELECT * FROM materiel')
    return (cursor,cur2,cur3) #the problem is here 

TypeError: 'sqlite3.Cursor' object is not subscriptable TypeError:“ sqlite3.Cursor”对象不可下标

You are trying to get item from cursor, that's why. 您正试图从光标中获取项目,这就是原因。

Function tree_select returns tuple of cursors: 函数tree_select返回游标的元组:

tree_select() -> (<sqlite3.Cursor>, <sqlite3.Cursor>, <sqlite3.Cursor>)

After it you iterate over these cursors: 之后,您遍历以下游标:

cur=issam.tree_select()
for i in cur:
    ...

After it you try to extract value by key from cursor(in each iteration step): 之后,您尝试通过游标从键中提取值(在每个迭代步骤中):

 tv.set('#{}'.format(i['ID']),'#Type',i['type'])    # i - is sqlite3.Cursor object

where i is a sqlite3.Cursor and fails with error: 'sqlite3.Cursor' object is not subscriptable 其中isqlite3.Cursor并失败并出现错误: 'sqlite3.Cursor' object is not subscriptable

Here is a small example, how to extract values as from dictionary: 这是一个小示例,说明如何从字典中提取值:

import sqlite3

def row2dict(cursor, row):
    result = dict()
    for idx, col in enumerate(cursor.description):
        result[col[0]] = row[idx]
    return result

db = sqlite3.connect(":memory:")
db.row_factory = row2dict
cursor = db.cursor()

cursor.execute("select 1 as ID, 'john' as name")
row = cursor.fetchone()
print row['ID'], row['name']

cursor.close()
db.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM