It is minimal example which create database with two elements and later it uses data from database to fill Treeview
You have to use create()
only once.
import tkinter as tk
from tkinter import ttk
import sqlite3
def create(con):
cur = con.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS user (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
town TEXT NOT NULL
);''')
cur.execute('INSERT INTO user (name, age, email, town) values("James Bond", 45, "[email protected]", "London")')
cur.execute('INSERT INTO user (name, age, email, town) values("Rambo", 45, "[email protected]", "Washington")')
con.commit()
# --- main ---
con = sqlite3.connect("user_info.db")
cur = con.cursor()
create(con)
root = tk.Tk()
tv = ttk.Treeview(root)
tv.pack(fill="both", expand=True)
tv.config(columns= ("name", 'age', 'email', 'town'))
tv.heading('#0', text="ID")
tv.column('#0', width = 100)
tv.heading('1', text = "Age")
tv.column('1', width = 100)
tv.heading('name', text="Name")
tv.column('name', width = 100)
tv.heading('2', text = "email")
tv.column("2", width = 100)
tv.heading('3', text = "Town")
tv.column("3", width = 100)
cur.execute('SELECT * FROM user')
for number, row in enumerate(cur.fetchall()):
print(row)
item = 'item{}'.format(number)
tv.insert("", 'end', item, text=row[0])
tv.set(item, 'name', row[1])
tv.set(item, 'age', row[2])
tv.set(item, 'email', row[3])
tv.set(item, 'town', row[4])
root.mainloop()
6
solved How to convert an SQL Output to a python list [closed]