使用来自 sql 的信息填充 Treeview?

Populate Treeview with info from sql?

我想就我下面的代码寻求一些建议:

from tkinter import *
from tkinter import ttk
import sqlite3

root = Tk()
root.geometry("500x500")
root.title("Inventory Balance")


def db():
    global conn, mycursor
    conn = sqlite3.connect('MyStock.sql3')
    mycursor = conn.cursor()


def data():`
    tree.delete(*tree.get_children())
    mycursor.execute("SELECT * FROM ItemCode")
    for row in myscursor:
        tree.insert('', 'end', values=row[1:6])

    conn.close()

frame = Frame(root)
frame.pack()

tree = ttk.Treeview(frame, columns = (1,2,3,4,5), height = 20, show = "headings")
tree.pack(side = 'top')

tree.heading(1, text="ItemCode")
tree.heading(2, text="Description")
tree.heading(3, text="Category")
tree.heading(4, text="Unit")
tree.heading(5, text="Quantity")

tree.column(1, width = 100)
tree.column(2, width = 100)
tree.column(3, width = 100)
tree.column(4, width = 100)
tree.column(5, width = 100)

# Inserting Scrollbar
scroll = ttk.Scrollbar(frame, orient="vertical", command=tree.yview)
scroll.pack(side = 'right', fill = 'y')

tree.configure(yscrollcommand=scroll.set)

root.mainloop()

我稍后必须将其用作主屏幕,添加按钮并在使用库存时显示不断更新的树视图,然后通过另一个 python tkinter 脚本进行更新。 我的主要问题是它读取了正确的列(ItemCode、Description、Category、Unit、Quantity),但是数据库中包含的信息没有显示在树视图中。

请提供帮助,如有需要请随时询问更多信息。

我按照建议编辑了脚本,但最终还是这样: enter image description here

再次感谢您

您的代码中有两个问题:

  • 在将记录插入树视图时使用 inforow应该用
  • treeview.insert(...) 需要两个位置参数:parentindex

所以改变:

info = mycursor.fetchall()
for row in info:
    tree.insert(values=(info[1], info[2], info[3], info[4], info[5]))

至:

for row in mycursor:
    tree.insert('', 'end', values=row[1:6])