Home > Net >  My code deletes last item in list and not the item i want
My code deletes last item in list and not the item i want

Time:10-10

I want to create a function where the user gets a list of users from the database and can choose to delete on of them from the database. It looks the way i want, i get all items in rows with a delete button for each and they are named correct. But the function doesnt seem to work the way i want. If i click any delete button the last user gets deleted. Im new to this so im sure i made a mistake but i dont know where.

def delete():
    conn = sqlite3.connect("database.db")
    c = conn.cursor()
    c.execute("DELETE FROM databasetable WHERE oid = "   str(i[5]))
    conn.commit()
    conn.close()

conn = sqlite3.connect("database.db")
c = conn.cursor()
c.execute("SELECT *, oid FROM databasetable")
listfromdatabase = c.fetchall()
conn.commit()
conn.close()

for i in listfromdatabase:
    label = Label(frameskidlararenamn, text=i[0])
    label.pack()
    button = Button(frameskidlarareknapp, text="Delete "   str(i[0]), command=delete)
    button.pack()

Any ideas?

CodePudding user response:

At the end of the loop for i in listfromdatabase: i is the last item. So the delete function delete this last item.

CodePudding user response:

Your definition of delete is set to target the fifth element of i

def delete():
    conn = sqlite3.connect("database.db")
    c = conn.cursor()
    c.execute("DELETE FROM databasetable WHERE oid = "   str(i[5]))
    conn.commit()
    conn.close()

You should instead pass in the oid to delete by changing the definition

def delete(oid):
    conn = sqlite3.connect("database.db")
    c = conn.cursor()
    c.execute("DELETE FROM databasetable WHERE oid = "   str(oid))
    conn.commit()
    conn.close()

CodePudding user response:

Check if this works, passing an argument to command with lambda Function.
changed lambda : delete(i[5]) to lambda item=i[5]: delete(item)

button1 = [None for _ in range(len(listfromdatabase))]
for n,i in enumerate(listfromdatabase):
    label = Label(frameskidlararenamn, text=i[0])
    label.pack()
    button1[n] = Button(frameskidlarareknapp, text="Delete "   str(i[0]),command=lambda item=i[5]: delete(item))
    button1[n].pack()
def delete(item):
    conn = sqlite3.connect("database.db")
    c = conn.cursor()
    c.execute("DELETE FROM databasetable WHERE oid = "   str(item))
    conn.commit()
    conn.close()

Just to be sure, check with two buttons with same name but different function. like

def printnum(num):
    #print num on a label or something
button = Button(frameskidlarareknapp, text="print num 1", command=lambda: printnum(1))
button.pack()
button = Button(frameskidlarareknapp, text="print num 2", command=lambda: printnum(2))
button.pack()
  • Related