python数据库(sqlite3)和treevi

2024-10-01 17:33:07 发布

您现在位置:Python中文网/ 问答频道 /正文

大家好,我的代码有问题,我试图在treeview上显示数据库中的表,但是我看不到这个错误“TypeError:'sqlite3.Cursor'object is not subscribable” 可能是因为我的数据库中有三个表这是我代码的一部分:

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'])

以下是数据库文件中的函数(在类中):

^{pr2}$

Tags: 代码textid数据库formattypecodetv
1条回答
网友
1楼 · 发布于 2024-10-01 17:33:07

TypeError: 'sqlite3.Cursor' object is not subscriptable

你正试图从游标获取项目,这就是原因。在

函数tree_select返回光标的元组:

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

之后,您将迭代这些光标:

^{pr2}$

之后,您尝试从游标(在每个迭代步骤中)按键提取值:

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

其中i是一个sqlite3.Cursor,失败时出现错误:'sqlite3.Cursor' object is not subscriptable

下面是一个小例子,如何从字典中提取值:

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

相关问题 更多 >

    热门问题