【问题标题】:How to display information from database sqlite3 using GUI Tkinter in Python in a specific format?如何使用 Python 中的 GUI Tkinter 以特定格式显示来自数据库 sqlite3 的信息?
【发布时间】:2021-05-01 18:58:19
【问题描述】:

我正在尝试从数据库中检索信息并以这种特定方式显示它:

名字:蝙蝠侠

价格:18 英镑

但我收到此错误:“TypeError: 'int' object is not subscriptable.”

我该如何解决这个问题?

c.execute("SELECT name, price FROM products WHERE id=02")
    records = c.fetchone()
    # print(records)

    print_products = ''
    for record in records:
        print_products += 'Name:' + str(record[0]) + '\n' + 'Price: £' + str(record[1])

    query_label = Label(frame, fg='darkblue', bg='darkgray', text=print_products)
    query_label.pack()

【问题讨论】:

    标签: python sqlite user-interface tkinter


    【解决方案1】:

    由于您只从结果中获取一条记录,records 是列值的元组。然后你使用for record in records:,这意味着record是一个可能是整数的列值。所以使用record[0] 会引发上述异常。

    其实你根本不需要 for 循环:

    c.execute("SELECT name, price FROM products WHERE id=02")
    record = c.fetchone()
    
    # check whether record exists
    if record:
        print_products = 'Name:' + str(record[0]) + '\n' + 'Price: £' + str(record[1])
    
        query_label = Label(frame, fg='darkblue', bg='darkgray', text=print_products)
        query_label.pack()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-13
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多