如何在Treeview中显示条目小部件内容

时间:2018-02-07 09:44:11

标签: python wpf tkinter treeview

entry db中保存后,我试图在treeview中显示输入sqlite3小部件的内容。内容已保存到db但未显示id {}}}中的1}},Fist nameSurname内容。

欢迎您提出建议。

treeview

1 个答案:

答案 0 :(得分:1)

代码中的问题是for items in fr不起作用。 Python将fr视为空的可迭代(在for循环中放置一个print语句,您将看到它永远不会被执行)。因此,要在树视图中插入数据,您可以直接从条目中获取数据并使用id检索数据库cur.lastrowid(我在问题content negotiation的答案中找到了此解决方案):

from tkinter import ttk
import tkinter as tk
import sqlite3


def connect():
    conn = sqlite3.connect("TRIAL.db")
    cur = conn.cursor()
    cur.execute("CREATE TABLE IF NOT EXISTS profile(id INTEGER PRIMARY KEY, First TEXT, Surname TEXT)")
    conn.commit()
    conn.close()



def Insert():
    conn = sqlite3.connect("TRIAL.db")
    cur = conn.cursor()
    data = (first_text.get(), surname_text.get())
    # insert data in db
    cur.execute("INSERT INTO profile (First, Surname) VALUES(?, ?)", data)  
    conn.commit()
    # insert data in treeview
    tree.insert('', tk.END, text=str(cur.lastrowid), values=data)  
    conn.close()


connect()  #  this to create the db

root = tk.Tk()
root.geometry("400x400")

tree= ttk.Treeview(root, column=("column", "colunn1"))
tree.heading("#0", text="NUMBER")
tree.heading("#1", text="FIRST NAME")
tree.heading("#2", text="SURNAME")
tree.pack()


first_text = tk.StringVar()
e1 = tk.Entry(root, textvariable=first_text)
e1.pack()
surname_text = tk.StringVar()
e2 = tk.Entry(root, textvariable=surname_text)
e2.pack()

b1 = tk.Button(text="add data", command=Insert)
b1.pack(side=tk.BOTTOM)

root.mainloop()

编辑:如果您使用的是“#1'”,#3;#2','#3'避免使用特殊的 列'#0',然后您需要更改位Insert:您需要在values而不是text中传递行ID。

from tkinter import ttk
import tkinter as tk
import sqlite3

def connect():
    conn = sqlite3.connect("TRIAL.db")
    cur = conn.cursor()
    cur.execute("CREATE TABLE IF NOT EXISTS profile(id INTEGER PRIMARY KEY, First TEXT, Surname TEXT)")
    conn.commit()
    conn.close()


def Insert():
    conn = sqlite3.connect("TRIAL.db")
    cur = conn.cursor()
    data = (first_text.get(), surname_text.get())
    # insert data in db
    cur.execute("INSERT INTO profile (First, Surname) VALUES(?, ?)", data)  
    conn.commit()
    # insert data in treeview
    tree.insert('', tk.END, values=(str(cur.lastrowid),) + data)  
    conn.close()


connect()  #  this to create the db

root = tk.Tk()
root.geometry("400x400")

tree = ttk.Treeview(root, column=("column1", "column2", "column3"), show='headings')
tree.heading("#1", text="NUMBER")
tree.heading("#2", text="FIRST NAME")
tree.heading("#3", text="SURNAME")
tree.pack()

first_text = tk.StringVar()
e1 = tk.Entry(root, textvariable=first_text)
e1.pack()
surname_text = tk.StringVar()
e2 = tk.Entry(root, textvariable=surname_text)
e2.pack()

b1 = tk.Button(text="add data", command=Insert)
b1.pack(side=tk.BOTTOM)

root.mainloop()