So basically I have an SQL database with 5 different columns of data. what I am trying to do is take the data from my SQL query and put it into a list so I can display it in tkinter’s treeview widget.
Questions:
Is there an easier way to take data from an SQL table and display it in a table-like format in tkinter? If so how?
Is it a good idea to make a table in tkinter with the treeview widget?
If not, what widget should I use?
I have tried to convert my SQL output to a list but it keeps giving errors similar to:
list index out of range
Here is my complete code:
from tkinter import * from tkinter import messagebox from tkinter import ttk import sqlite3 #lst = ['apple', 'banana', 'strawberry', 'avo', 'rasberry'] con = sqlite3.connect("user_info.db") cur = con.cursor() root = Tk() tv = ttk.Treeview(root) tv.pack() 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') fr = cur.fetchall() print(fr)c print(cur) tv.insert("",'0', 'item1', text = fr[0]) tv.set('item1', 'name', fr[1]) tv.set('item1', 'age', fr[2]) tv.set('item1', 'email', fr[3]) tv.set('item1', 'town', fr[4]) root.mainloop()
Sorry for the weird layout
Advertisement
Answer
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, "bond@mi6.uk", "London")') cur.execute('INSERT INTO user (name, age, email, town) values("Rambo", 45, "rambo@usa.com", "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()