selected_item = trv.selection()[0]
from tkinter import ttk
import tkinter as tk
from sqlalchemy import create_engine, text
from sqlalchemy.exc import SQLAlchemyError
my_conn = create_engine("mysql+mysqldb://root:test@localhost/my_tutorial")
my_conn = my_conn.connect() # Establish a connection to the MySQL database
r_set = my_conn.execute(text('SELECT * FROM student LIMIT 0,10'))
my_w = tk.Tk() # Create the main Tkinter window
my_w.geometry('400x350') # Set window dimensions
my_w.title('www.plus2net.com') # Set window title
trv = ttk.Treeview(my_w, selectmode='browse')
trv.grid(row=1, column=1, padx=20, pady=20)
trv['columns'] = ('1', '2', '3', '4', '5')
trv['show'] = 'headings'
trv.column('1', width=30, anchor='c')
trv.column('2', width=80, anchor='c')
trv.column('3', width=80, anchor='c')
trv.column('4', width=80, anchor='c')
trv.column('5', width=80, anchor='c')
trv.heading('1', text='id')
trv.heading('2', text='Name')
trv.heading('3', text='Class')
trv.heading('4', text='Mark')
trv.heading('5', text='Gender')
for dt in r_set:
trv.insert("", 'end', iid=dt[0],
values=(dt[0], dt[1], dt[2], dt[3], dt[4]))
b1 = tk.Button(my_w, text='delete row', width=20, bg='yellow',
command=lambda: my_delete())
b1.grid(row=2, column=1)
my_str = tk.StringVar()
l1 = tk.Label(my_w, textvariable=my_str, font=('times', 10, ''))
l1.config(fg='blue')
l1.grid(row=3, column=1)
my_str.set('Message here')
def my_delete():
selected_item = trv.selection()[0] # Get the selected row ID
try:
query = "DELETE FROM student WHERE id=:delete_id"
rs = my_conn.execute(text(query), {'delete_id': selected_item})
if rs.rowcount == 1: # Confirm deletion
my_conn.commit() # Commit the transaction
trv.delete(selected_item) # Remove from Treeview
l1.config(fg='green')
my_str.set('Record deleted')
except SQLAlchemyError as e:
error = str(e.__dict__.get('orig', e))
l1.config(fg='red')
my_str.set(error)
l1.after(3000, lambda: my_str.set(''))
from tkinter import ttk
import tkinter as tk
from sqlalchemy import create_engine, text
from sqlalchemy.exc import SQLAlchemyError
my_conn = create_engine("mysql+mysqldb://id:pw@localhost/my_db")
my_conn = my_conn.connect() # connection string or connection object
r_set = my_conn.execute(text('SELECT * FROM student LIMIT 0,10'))
my_w = tk.Tk()
my_w.geometry('400x350') # width and height of the window
my_w.title("www.plus2net.com") # adding title to window
trv = ttk.Treeview(my_w, selectmode='browse') # treeview object
trv.grid(row=1, column=1, padx=20, pady=20) # placed on Grid layout
trv["columns"] = ("1", "2", "3", "4", "5")
trv['show'] = 'headings'
# trv['show']='tree'
trv.column("1", width=30, anchor='c')
trv.column("2", width=80, anchor='c')
trv.column("3", width=80, anchor='c')
trv.column("4", width=80, anchor='c')
trv.column("5", width=80, anchor='c')
trv.heading("1", text="id")
trv.heading("2", text="Name")
trv.heading("3", text="Class")
trv.heading("4", text="Mark")
trv.heading("5", text="Gender")
for dt in r_set: # adding rows of MySQL data to treeview
# print(dt)
trv.insert("", 'end', iid=dt[0],
values=(dt[0], dt[1], dt[2], dt[3], dt[4]))
b1 = tk.Button(my_w, text='delete row', width=20, bg='yellow',
command=lambda: my_delete())
b1.grid(row=2, column=1)
my_font = ('times', 10, '')
my_str = tk.StringVar()
l1 = tk.Label(my_w, textvariable=my_str, font=my_font)
l1.config(fg='blue')
l1.grid(row=3, column=1)
my_str.set("Message here") # print(my_error)
def my_delete():
selected_item = trv.selection()[0] # get selected row id
try:
query = "DELETE FROM student WHERE id=:delete_id"
rs = my_conn.execute(text(query), {'delete_id': selected_item})
if rs.rowcount == 1: # confirm that row is deleted
my_conn.commit() # Commit the delete operation to the database
trv.delete(selected_item) # delete from Treeview
l1.config(fg='green') # message font colour
my_str.set("Record deleted") # Success message
except SQLAlchemyError as e: # error in deleting
error = str(e.__dict__.get('orig', e))
l1.config(fg='red')
my_str.set(error) # show error message
l1.after(3000, lambda: my_str.set('')) # remove the message
l1.after(6000, lambda: my_str.set(''))
my_w.mainloop()
from tkinter import ttk
import tkinter as tk
from tkinter import messagebox
from sqlalchemy import create_engine, text
from sqlalchemy.exc import SQLAlchemyError
b1 = tk.Button(my_w, text='delete row', width=20, bg='yellow',
command=lambda: confirm_delete())
b1.grid(row=2, column=1)
def confirm_delete():
selected_item = trv.selection()
if not selected_item: # Ensure a row is selected
messagebox.showwarning('Warning', 'Please select a row to delete.')
return
response = messagebox.askyesno('Confirm Delete', 'Are you sure you want to delete this record?')
if response: # User confirms deletion
my_delete(selected_item[0])
def my_delete(selected_item):
try:
query = "DELETE FROM student WHERE id=:delete_id"
rs = my_conn.execute(text(query), {'delete_id': selected_item})
if rs.rowcount == 1: # Confirm row deletion
my_conn.commit() # Commit changes
trv.delete(selected_item) # Remove from Treeview
l1.config(fg='green')
my_str.set('Record deleted')
except SQLAlchemyError as e:
error = str(e.__dict__.get('orig', e))
l1.config(fg='red')
my_str.set(error)
l1.after(3000, lambda: my_str.set(''))
from tkinter import ttk
import tkinter as tk
from tkinter import messagebox
from sqlalchemy import create_engine, text
from sqlalchemy.exc import SQLAlchemyError
my_conn = create_engine("mysql+mysqldb://id:pw@localhost/my_db")
my_conn = my_conn.connect() # connection string or connection object
r_set = my_conn.execute(text('SELECT * FROM student LIMIT 0,10'))
my_w = tk.Tk()
my_w.geometry('400x350') # width and height of the window
my_w.title("www.plus2net.com") # adding title to window
trv = ttk.Treeview(my_w, selectmode='browse') # treeview object
trv.grid(row=1, column=1, padx=20, pady=20) # placed on Grid layout
trv["columns"] = ("1", "2", "3", "4", "5")
trv['show'] = 'headings'
trv.column("1", width=30, anchor='c')
trv.column("2", width=80, anchor='c')
trv.column("3", width=80, anchor='c')
trv.column("4", width=80, anchor='c')
trv.column("5", width=80, anchor='c')
trv.heading("1", text="id")
trv.heading("2", text="Name")
trv.heading("3", text="Class")
trv.heading("4", text="Mark")
trv.heading("5", text="Gender")
for dt in r_set: # adding rows of MySQL data to treeview
trv.insert("", 'end', iid=dt[0],
values=(dt[0], dt[1], dt[2], dt[3], dt[4]))
b1 = tk.Button(my_w, text='delete row', width=20, bg='yellow',
command=lambda: confirm_delete())
b1.grid(row=2, column=1)
my_font = ('times', 10, '')
my_str = tk.StringVar()
l1 = tk.Label(my_w, textvariable=my_str, font=my_font)
l1.config(fg='blue')
l1.grid(row=3, column=1)
my_str.set("Message here")
def confirm_delete():
"""Show a confirmation dialog before deleting."""
selected_item = trv.selection()
if not selected_item: # Check if a row is selected
messagebox.showwarning("Warning", "Please select a row to delete.")
return
response = messagebox.askyesno("Confirm Delete", "Are you sure you want to delete this record?")
if response: # User clicked Yes
my_delete(selected_item[0])
def my_delete(selected_item):
"""Delete the selected item from the database and Treeview."""
try:
query = "DELETE FROM student WHERE id=:delete_id"
rs = my_conn.execute(text(query), {'delete_id': selected_item})
if rs.rowcount == 1: # Confirm that row is deleted
my_conn.commit() # Commit the transaction
trv.delete(selected_item) # Delete from Treeview
l1.config(fg='green') # Success message color
my_str.set("Record deleted")
except SQLAlchemyError as e: # Handle any SQL errors
error = str(e.__dict__.get('orig', e))
l1.config(fg='red')
my_str.set(error)
l1.after(3000, lambda: my_str.set('')) # Clear the message after 3 seconds
my_w.mainloop()
Display MySQL records in Treeview Pagination of MySQL records in Treeview
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.