I want to delete a row from a sqlite3 database using the selection of a combobox to get the row that I want to delete. My current code deletes an item from the combobox, but when I restart code, the value appears again. This is because it is not getting deleted from the database. Could someone please help me with this? Thank you very much.
Code:
from tkinter import *
import os
import sqlite3
from tkinter import _setit
# init window
window=Tk()
window.title("Scheduling Assistant")
window.geometry("400x300")
addname1 = Label(text="Add Last Name:")
addname = Entry()
addquality1 = Label(text="Add Quality (A,B, or C):")
addquality = Entry()
addname1.pack()
addname.pack()
addquality1.pack()
addquality.pack()
# create table
conn = sqlite3.connect("dentist0.db")
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS densist(
last_name text,
class text)""")
options = StringVar()
om1 = OptionMenu(window, options, [])
def update_menu():
c.execute("SELECT last_name FROM densist")
# changed 'all' to 'result' as 'all' is a built-in function of Python
result = c.fetchall()
print(result)
om1['menu'].delete(0, 'end')
for choice in result:
# used choice[0] instead of choice
# use class '_setit' to set the tkinter variable when an item is selected
om1['menu'].add_command(label=choice[0], command=_setit(options, choice[0]))
def my_remove_sel():
om1['menu'].delete(options.get())
options.set('') # clear selection after the selected item is deleted
def click1():
lstnme = addname.get()
quality = addquality.get()
sql = "INSERT INTO densist VALUES (?,?)"
c.execute(sql, [lstnme, quality])
conn.commit()
update_menu()
submit = Button(text='Add',command=click1)
submit2=Button(text='Delete', command=my_remove_sel)
submit.pack()
submit2.pack()
om1.pack()
update_menu()
window.mainloop()
There are issues when you are inserting items into the option menu:
for choice in all:
om1['menu'].add_command(label=choice)
choice
is a tuple, so you are using a tuple as item in the option menu. Use choice[0]
in .add_command()
instead..add_command(label=choice)
will not update the tkinter variable options
when an item is selected. You need to use the undocumented class _setit
in the tkinter module to do it (it is used internally by OptionMenu
class)....
from tkinter import _setit
...
def update_menu():
c.execute("SELECT last_name FROM densist")
# changed 'all' to 'result' as 'all' is a built-in function of Python
result = c.fetchall()
print(result)
om1['menu'].delete(0, 'end')
for choice in result:
# used choice[0] instead of choice
# use class '_setit' to set the tkinter variable when an item is selected
om1['menu'].add_command(label=choice[0], command=_setit(options, choice[0]))
def my_remove_sel():
lastname = options.get()
# remove from database
c.execute('DELETE FROM densist WHERE last_name = ?', [lastname])
conn.commit()
# remove from option menu
om1['menu'].delete(lastname)
options.set('') # clear selection after the selected item is deleted