首页 > 解决方案 > 如何从数据库中删除或编辑记录

问题描述

我为我糟糕的英语提前道歉......我是编程世界的新手,所以我真的不知道我在做什么。我正在尝试用 Python,Tkinter 制作一个基本的通讯录。我设法以某种方式编写代码以在数据库中添加记录,但无法编写代码以删除或编辑选定的记录。帮助将不胜感激

import datetime
import tkinter
from tkinter import *
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
import sqlite3


def date_for_humans():
    date = datetime.datetime.now().date()
    date = str(date)
    x = date.split("-")
    return x[2] + "." + x[1] + "." + x[0] + "."


# creating windows for show contact
def add():
    kontakti = Toplevel()
    kontakti.title("Lista kontakta")
    kontakti.iconbitmap(r"phonebookicon.ico")
    kontakti.geometry("400x500")
    kontakti.resizable(False, False)

    def submit():
        # create data base or connect to one
        conn = sqlite3.connect("Imenik.db")

        # create cursor
        c = conn.cursor()

        # insert into a table
        c.execute("INSERT INTO Kontakti VALUES (:f_name, :l_name, :number)",
                  {
                    "f_name": f_name.get(),
                    "l_name": l_name.get(),
                    "number": number.get()
                  })

        # commint changes
        conn.commit()

        conn.close()

        f_name.delete(0,END)
        l_name.delete(0, END)
        number.delete(0, END)

    # creating and coloring top frame
    topframe = tk.Frame(kontakti, height=150, bg="#ffffff")
    topframe.pack(fill=X)

    # creating and coloring bottom farame
    bottomframe = tk.Frame(kontakti, height=350, bg="#34ebeb")
    bottomframe.pack(fill=X)

    # creating text at the top of app:
    text2 = Label(kontakti, text="DODAVANJE KONTAKTA", font="ariel 15 bold", bg="#ffffff", fg="black")
    text2.place(x=80, y=20)

    # creating close button
    button1 = Button(kontakti, text="Zatvori prozor", bg="white", fg="black",
                     activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=kontakti.destroy)
    button1.place(x=295, y=465)

    # create text boxes
    f_name = Entry(kontakti, width=30)
    f_name.place(x=80, y=200, height=20)
    l_name = Entry(kontakti, width=30)
    l_name.place(x=80, y=230, height=20)
    number = Entry(kontakti, width=30)
    number.place(x=80, y=260, height=20)

    # create text box labels
    f_name_label = Label(kontakti, text="Ime", bg="#34ebeb")
    f_name_label.place(x=20, y=200)
    l_name_label = Label(kontakti, text="Prezime", bg="#34ebeb")
    l_name_label.place(x=20, y=230)
    number_label = Label(kontakti, text="Broj", bg="#34ebeb")
    number_label.place(x=20, y=260)

    # create sumbit button
    submint_btn = Button(kontakti, text="Dodaj kontakt", bg="white", fg="black",
                         activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=submit)
    submint_btn.place(x=40, y=320)


def edit():

    c.execute("UPDATE Kontakti SET f_name=?, l_name=?, number=? WHERE f_name= ? AND l_name = ? AND number=?",
              (new_value_for_f_name, new_value_for_l_name, new_value_for_number, f_name, l_name, number))
    conn.commit()


def delete():

    f_name = listbox.curselection()[0]
    l_name = listbox.curselection()[1]
    number = listbox.curselection()[2]

    c.execute("DELETE * FROM Kontakti WHERE f_name = ? AND l_name = ? AND number = ?", (f_name, l_name, number))
    conn.commit()


def leave():
    root.destroy()


# creating a main window:
root = Tk()
root.title("Imenik App")
root.iconbitmap(r"phonebookicon.ico")
root.geometry("650x550")
root.resizable(False, False)

# creating and coloring top frame:
topFrame = tk.Frame(root, height=150, bg="#ffffff")
topFrame.pack(fill=X)


# creating and coloring bottom frame:
bottomFrame = tk.Frame(root, height=500, bg="#34ebeb")
bottomFrame.pack_propagate(False)
bottomFrame.pack(fill=X)

listbox = Listbox(bottomFrame)
listbox.place(x=40, y=40, height=340, width=200)
scrollbar = Scrollbar(bottomFrame)
scrollbar.place(height=340, x=240, y=40)

# Insert elements into the listbox

conn = sqlite3.connect("Imenik.db")
c = conn.cursor()
a = c.execute("SELECT *,oid FROM Kontakti")
records = c.fetchall()

for record in records:
    listbox.insert(END, str(record[0]) + " " + str(record[1]))

listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=listbox.yview)

# creating text at the top of app:
text1 = Label(root, text="IMENIK", font="ariel 35 bold", bg="#ffffff", fg="black")
text1.place(x=240, y=40)

# displaying date and time at the top of app:

datel = Label(root, text="Danasnji datum: " + date_for_humans(), font="ariel 10 bold", bg="#ffffff", fg="black")
datel.place(x=450, y=125)

# displaying icon at the top of the app:
image1 = Image.open("phonebook1.png")
image1 = image1.resize((90, 90), Image.ANTIALIAS)
image = ImageTk.PhotoImage(image1)
label1 = tkinter.Label(image=image, bg="#ffffff")
label1.image = image
label1.place(x=80, y=30)

conn.commit()
conn.close()


'''
# create data base or connect to one
conn = sqlite3.connect("Imenik.db")

# create cursor
c = conn.cursor()

# create table

c.execute("""CREATE TABLE kontakti (
        first_name txt,
        last_name txt,
        number integer
        )""")


# commint changes
conn.commit()

conn.close()
'''

# adding button 1, add contacts
viewButton = Button(root, text="Dodaj kontakt", pady=10, padx=70, bg="white", fg="black",
                    activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=add)
viewButton.place(x=380, y=200)

# adding button 2, edit contacts
addButton = Button(root, text="Izmeni kontakt", pady=10, padx=67, bg="white", fg="black",
                   activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=edit)
addButton.place(x=380, y=260)

# adding button 3, delete contacts
deleteButton = Button(root, text="Obrisi kontakt", pady=10, padx=70, bg="white", fg="black",
                      activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=delete)
deleteButton.place(x=380, y=320)

# adding button 4, exit button
exitButton = Button(root, text="Izlaz", pady=5, padx=50, bg="white", fg="black",
                    activebackground="#A9A9A9", font=("Helvetica", 10, "bold"), command=leave)
exitButton.place(x=505, y=510)

root.mainloop()

如果有任何不清楚的地方,请询问我真的需要帮助。提前致谢!

标签: pythonsqlitetkinter

解决方案


您好,欢迎来到 Stack Overflow。为了让您知道鼠标选择了哪些数据,您可以使用以下方式:

name_of_listbox.curselection()

这将返回当前选定行的内容列表。它给了我们一个列表,因为有一个选项可以在ListBox. 您可以遍历每个并从中获取数据。将数据存储在变量中并将它们用于UPDATEDELETE命令。

编辑:

对于删除记录:

f_name = listbox.curselection()[0]
l_name = listbox.curselection()[1]
number = listbox.curselection()[2]

c1.execute("DELETE * FROM Kontakti WHERE f_name = ? AND l_name = ? AND number = ?", (f_name, l_name, number))
conn1.commit()

用于修改值:

c1.execute("UPDATE Kontakti SET f_name=?, l_name=?, number=? WHERE f_name= ? AND l_name = ? AND number=?",(new_value_for_f_name,new_value_for_l_name,new_value_for_number, f_name, l_name, number))
conn1.commit()

我完全不明白您从单个列表框中选择名字、姓氏和数字的方式。所以我保持列表框的名称相同。


推荐阅读