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. Only the delete button for item 1 on the list "works". But if you click that button you delete the last item on the list and not the first. All the other delete-buttons doesnt seem to do anything. 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
for i in listfromdatabase:
label = Label(frameskidlararenamn, text=i[0])
label.pack()
button = Button(frameskidlarareknapp, text="Delete " str(i[0]),command=lambda: delete(i[5]))
button.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()