【问题标题】:How do I use tkinter 'Treeview' to list items in a table of a database?如何使用 tkinter 'Treeview' 列出数据库表中的项目?
【发布时间】:2018-05-10 22:22:59
【问题描述】:

我有一个 SQLite 数据库,我将读取该数据库并将其中一个表数据列出到树视图中。为了让它发挥作用,我一直在寻找很长时间,我正在努力寻找任何对我有用或有意义的东西。例如,在我的表格中,我有标题“会员 ID”和“全名”。

出于测试目的,我创建了存储这些值的字符串的变量。

root = Tk()

name = "cameron"
id="223344"

lblsearchName = Label(root, text="Full Name:")
lblsearchName.grid(sticky=E)
searchEntry = Entry(root)
searchEntry.grid(column=1, sticky=E)

treeView = ttk.Treeview(root)
treeView.grid(columnspan=2)

root.mainloop()

如何根据我的数据库表中的标题在树视图中创建标题? 我现在如何读取数据库,但我需要知道如何将这些值插入到树视图中。 (对于这个例子'name'和'id')

【问题讨论】:

    标签: python sqlite tkinter treeview tkinter-layout


    【解决方案1】:
    # set up the columns and headings
    # In reality "Member ID" would be exported from the database
    treeview["columns"] = ["Member ID", "Full Name"]
    treeview["show"] = "headings"
    treeview.heading("Member ID", text="Member ID")
    treeview.heading("Full Name", text="Full Name")
    
    # Add content using (where index is the position/row of the treeview)
    # iid is the item index (used to access a specific element in the treeview)
    # you can set iid to be equal to the index
    tuples = [(1, "Name1"),(2, "Name2")]
    index = iid = 0
    for row in tuples:
        treeView.insert("", index, iid, values=row)
        index = iid = index + 1
    

    样本输出:

    更多关于heading的信息。

    更多关于insert的信息。

    更多关于options (E.g. columns and headings)的信息

    【讨论】:

    • 出现错误。 'C:\Users\User\AppData\Local\Programs\Python\Python36\python.exe C:/Users/User/OneDrive/PycharmProjects/TKinter/treeView.py 文件“C:/Users/User/OneDrive/PycharmProjects/ TKinter/treeView.py",第 18 行 treeView.["show"] = "headings" ^ SyntaxError: invalid syntax'
    • 是的,抱歉,不小心添加了一个“。”复制时。应该是固定的。
    • 太棒了!非常感谢。你能不能详细说明一下 index 和 iid 我仍然不确定它们到底是什么。我将它们设置为 0,1,效果很好,但这是一个幸运的猜测。
    • index 是放置信息的位置/行。 iid 是赋予信息的项目标识符,可用于访问它。如果设置这个等于索引,在使用其他treeview方法时,基本上可以使用索引来访问信息。例如,您使用 iid 删除行。
    • 好的,当我从数据库中获取数据时,它给了我多个元组。然后我将如何将此元组的每个元素插入到树视图中。 (很抱歉再次打扰您)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 2013-05-19
    • 2016-05-25
    • 1970-01-01
    • 2013-08-15
    相关资源
    最近更新 更多