如何从sqlite数据库中删除组合框的选择?



我想从sqlite3数据库中删除一行,使用组合框的选择来获得我想要删除的行。我当前的代码从组合框中删除了一个项目,但是当我重新启动代码时,该值再次出现。这是因为它没有从数据库中删除。有人能帮我一下吗?非常感谢。

代码:

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()

在选项菜单中插入项目时存在问题:

for choice in all:
om1['menu'].add_command(label=choice)
  • choice是一个元组,因此您使用元组作为选项菜单中的项。用choice[0]代替.add_command()
  • .add_command(label=choice)将不更新tkinter变量options当一个项目被选中。您需要在tkinter模块中使用未记录的类_setit来完成此操作(它由OptionMenu类在内部使用)。
...
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

最新更新