【问题标题】:Populate Treeview with info from sql?使用来自 sql 的信息填充 Treeview?
【发布时间】:2020-03-18 13:08:10
【问题描述】:

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

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

再次感谢您

【问题讨论】:

  • 为什么你的代码在向树视图插入数据时使用info[1], info[2], ...?应该改为row[1], row[2], ... 吗?还有为什么索引是从 1 开始,而不是 0?

标签: python-3.x tkinter treeview


【解决方案1】:

您的代码中有两个问题:

  • 在树视图中插入记录时使用info。应该使用row
  • 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])

【讨论】:

  • 请在上面找到已编辑的帖子以确认任何故障。我添加了一个指向图像的链接以显示输出。
  • 你有没有得到任何错误?尝试将结果打印到控制台,看看是否实际返回了记录。
  • 更新后的代码中有错字:for row in myscursor: 应该是 for row in mycursor:。此外,您的代码没有调用db()data(),因此不会显示任何数据。
  • 对不起,错字,它只是在帖子上,而不是运行有错字的脚本。我尝试使用代码截取 tkinter 窗口以显示更新。没有错误代码。它只声明“进程以退出代码 0 结束”
  • 我应该在哪里添加“呼叫”功能?这是我第一个更大的集成 tkinter 项目,澄清一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-25
  • 1970-01-01
  • 1970-01-01
  • 2017-04-18
  • 1970-01-01
  • 2014-07-08
  • 1970-01-01
相关资源
最近更新 更多