I'm building a libary management system in python using tkinter and sqlite3. made some entry widgets for the user to input book_id, book_name and author:
from tkinter import *
import sqlite3
root = Tk()
root.geometry('1350x750')
entry_id_book = Entry(root, width=30)
entry_id_book.pack()
entry_book_name = Entry(root, width=30)
entry_book_name.pack()
entry_author = Entry(root, width=30)
entry_author.pack()
connect to a database
conn = sqlite3.connect('library.db')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS books (
id_book int PRIMARY KEY,
book_name text,
author text
)""")
conn.commit()
conn.close()
and a treeview widget where I'll display the data
tree = ttk.Treeview(root, show='headings')
tree['columns'] = ('Book ID', 'Book Name', 'Author')
tree.column('#0', width=0, stretch=0, anchor=CENTER)
tree.column('Book ID', anchor=CENTER, width=100)
tree.column('Book Name', anchor=CENTER, width=250)
tree.column('Author', anchor=CENTER, width=150)
tree.heading('#0', text='', anchor=CENTER)
tree.heading('Book ID', text='Book ID', anchor=CENTER)
tree.heading('Book Name', text='Book Name', anchor=CENTER)
tree.heading('Author', text='Author', anchor=CENTER)
tree.pack()
a function to take those inputs and load the data into the database
def load_data():
conn = sqlite3.connect('library.db')
c = conn.cursor()
c.execute('INSERT INTO books VALUES(:id_book, :book_name, :author)',
{
'id_book': entry_id_book.get(),
'book_name': entry_book_name.get(),
'author': entry_author.get()
})
conn.commit()
conn.close()
and another function to print those into a treeview widget
def display_data():
conn = sqlite3.connect('library.db')
c = conn.cursor()
c.execute('SELECT * FROM books')
list_book = c.fetchall()
for book in list_book:
tree.insert('', END, values=book)
conn.commit()
conn.close()
the buttons for the 2 functions above:
bt_load = Button(root, text='Load', command=load_data)
bt_load.pack()
bt_display = Button(root, text='Display', command=display_data)
bt_display.pack()
It will load and display those books just fine:
Book ID Book Name Author
but when I load a new book into the database and press Display button one more time, it will show me duplicates of all the other previous book data plus the new one:
Book ID Book Name Author
I know there must be something wrong with my for loop in the display_data function, but I suck at programming logic so I can't figure out what's wrong with it. How can I display each different line only once?