This is my code, its the start of my uni assignment and i’m somewhat new to coding / python.
i’m trying to make my code work so that when i open the tk, i can view the books i’ve stored in my DB (works) i can search for a specific book name, author or publish date and it’ll pull those (works) if i DELETE a book it’ll delete from the interface open, but does not update into my DB to delete the book from their too, how would i approach this 🙂
import tkinter as tk
from tkinter import ttk
import sqlite3
conn = sqlite3.connect("books.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM Books")
results = cursor.fetchall()
def delete():
selected_item = tree_view.selection() #get selected item
if tree_view.delete(selected_item):
x = selected_item[0]
tree_view.delete(x)
sql = 'DELETE FROM Books WHERE ID = %S'
cursor.execute(sql, (x,))
conn.commit()
def search_for_books():
global search_entry
search_term = search_entry.get().strip()
if not search_term:
print("Search term is empty.")
return
for item in tree_view.get_children():
tree_view.delete(item)
# Construct and execute the SQL query
query = "SELECT * FROM Books WHERE Book_Name LIKE ? OR Author LIKE ? OR Publish_Date LIKE ?"
search_pattern = f"%{search_term}%"
cursor.execute(query, (search_pattern, search_pattern, search_pattern))
rows = cursor.fetchall()
print("Rows found:", rows)
# Display the results in the tree view
for row in rows:
tree_view.insert("", tk.END, text=row[1], values=(row[2], row[3]))
root = tk.Tk()
tree_view = ttk.Treeview(columns=("Author", "Publish Date"))
tree_view.heading("#0", text="Book Name")
tree_view.heading("Author", text="Author")
tree_view.heading("Publish Date", text="Publish Date")
tree_view.pack()
for row in results:
tree_view.insert("", tk.END, text=row[1], values=(row[2], row[3]))
search_entry = tk.StringVar()
tk.Entry(root,textvariable=search_entry).pack()
tk.Button(root, text="Search", command=search_for_books).pack()
ttk.Button(root, text= "Delete", command= delete).pack(pady=10)
root.mainloop()
New contributor
Turnbull95 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2