Search code examples
pythontkintercomboboxttk

Remove an item from TTK Combobox List


I am currently trying to figure out how to remove an item from a combobox dropdown list. Currently for my delete button I have the following code:

def prof_del_btn():
    conn = sqlite3.connect('Doom.db')
    c = conn.cursor()

    name=prof_input.get()
    c.execute("SELECT prof FROM profile")
    rows=c.fetchall()

    if (name,) in rows:
        delProf = c.execute('DELETE from profile WHERE prof = "{}"'.format(name))
        prof_input.set('')
        print('Profile {} has been deleted'.format(name))
        prof_input['values'] = (prof_input['values'])
    else:
        prof_input.set('')
        print('Profile Doesn\'t Exist')

    conn.commit()
    conn.close()

Please note, I was playing around with it and just cannot figure this out. Currently in my sql db I have "nat" and "two" under the profile and what I am trying to do is remove "two".

I am not currently using classes as I'm not too sure how to use them properly at the moment. How would I reload the list?


Solution

  • You can get the current values from the Combobox and remove the required item from the list and then update the values. Also you don't need to execute the SELECT statement before DELETE statement. Below is modified code:

    def prof_del_btn():
        name = prof_input.get()
        if name:
            with sqlite3.connect('doom.db') as conn:
                c = conn.cursor()
                c.execute('DELETE FROM profile WHERE prof = ?', (name,))
                if c.rowcount > 0:
                    print('Profile {} has been deleted'.format(name))
                    options = list(prof_input['values'])
                    options.remove(name)
                    prof_input['values'] = options
                else:
                    print('Profile {} does not exist'.format(name))
                prof_input.set('')
                conn.commit()