Reputation: 597
Am having issue with how output all records in my sqlite3
db into tkinter treeview
.It outputs only the last record in the db
and also the records doesn't appear at the column specified for it.The print
method print all the db
records to my terminal but doesn't output all the records to the treeview
widget.
Your suggestions are welcome to achieve this
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 View():
conn = sqlite3.connect("TRIAL.db")
cur = conn.cursor()
cur.execute("SELECT * FROM profile")
rows = cur.fetchall()
for row in rows:
print(row) # it print all records in the database
tree.insert("", tk.END, values=row)
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()
b2 = tk.Button(text="view data", command=View)
b2.pack()
root.mainloop()
Upvotes: 0
Views: 12565
Reputation: 16169
There are two issues in your code:
tree.insert("", tk.END, values=row)
is not inside the for loop, so only the last row will be inserted in the treeview. The second is that the column #0
is a special column, and its value is set with text=...
, not with values=(...)
. To display correctly your data, you have at least two alternatives:
tree.insert("", tk.END, values=row)
by tree.insert("", tk.END, text=row[0], values=row[1:])
The second is not to use the special column #0
, you don't need it because you are using the treeview as a table. When you create the tree, use the option show='headings'
to hide column #0
and create 3 columns:
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 View():
conn = sqlite3.connect("TRIAL.db")
cur = conn.cursor()
cur.execute("SELECT * FROM profile")
rows = cur.fetchall()
for row in rows:
print(row) # it print all records in the database
tree.insert("", tk.END, values=row)
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()
b2 = tk.Button(text="view data", command=View)
b2.pack()
root.mainloop()
Upvotes: 7