Home > Back-end >  How to delete selected item on python treeview from the mysql table?
How to delete selected item on python treeview from the mysql table?

Time:03-30

I'm trying to delete a selected record from treeview and from the database Mysql at the same time. The insertion of the records from the database to treeview and the deletion of a selected record from treeview worked.

But my question is how to delete the selected record from database also?

manage_database = Frame(side_menu_bar, height=605, width=950, bg="#FEFEFC") manage_database.place(relx=0.5, rely=0.5, anchor=CENTER)

sql= "SELECT * FROM employeeInfo"
mycursor.execute(sql)
rows=mycursor.fetchall()

tv=ttk.Treeview(manage_database,columns=(1,2,3,4,5),show="headings",height="25")

manage_heading=ttk.Style()
manage_heading.configure('Treeview.Heading',background=light_gray,font=(family_font,H5,'bold'))
tv.place(relx=0.5,rely=0.5, anchor=CENTER)
tv.pack()

tv.column('#1',anchor=CENTER)
tv.heading('#1', text="ID")
tv.column('#2',anchor=CENTER)
tv.heading('#2', text="First name")
tv.column('#3',anchor=CENTER)
tv.heading('#3', text="Last name")
tv.column('#4',anchor=CENTER)
tv.heading('#4', text="Email")
tv.column('#5',anchor=CENTER)
tv.heading('#5', text="Phone number")

for i in rows:
    tv.insert('','end',values=i)

manageData = Frame(manage_database, height=60, width=950, bg="white")
manageData.place(x=475, y=575, anchor=CENTER)

# Style the selected records  
style.configure("Treeview", background="#E1E1E1")
style.map('Treeview', background=[('selected', dark_gray)])


# Delete the selected from treeview
def removeRecord():
    x = tv.selection()[0]
    tv.delete(x)`

CodePudding user response:

Suggest to set the iid option to the ID from the table:

for i in rows:
    tv.insert('', 'end', iid=i[0], values=i) # assume ID is the first column in the table

Then you can delete the record from table inside removeRecord() as below:

def removeRecord():
    selected = tv.selection()
    if selected:
        # a row is selected
        x = selected[0]
        tv.delete(x)
        # delete record from table
        sql = 'DELETE FROM employeeInfo WHERE ID = %s'
        mycursor.execute(sql, (x,))
        # assume mydb is the connection object of MySQL database
        mydb.commit()  # make sure to commit the change
  • Related