Remove Item from Listbox Python

Remove Item from Listbox Python

I am trying to remove an item from a listbox that is connected to a function from my checkbutton.

ShrimpTempVar=DoubleVar()
ShrimpTempCheck=Checkbutton(menu,variable = ShrimpTempVar, onvalue=5.99, offvalue=0,command=ShrimpTempuraOrder) 

def ShrimpTempuraOrder():
    if ShrimpTempVar.get()==5.99:
        qty=int(QTY2Var.get())
        finalprice=ShrimpTempVar.get()*qty
        listbox.insert(END, "Shrimp Tempura")
        listboxprice.insert( END, finalprice)
    elif ShrimpTempVar.get()==0:
        listbox.delete(0,END)
        listboxprice.delete(0,END)

I would like the item to be removed when I unselect it. In another post, it was suggested to do something like this:

listBox.Items.Delete(listbox.Items.IndexOf('Calamari'));

but it says that Listbox has no attribute in Items

In addition, I do not know the index number, since it changes due to the order in which I select the different checkbuttons.

Thanks for any help!

1 Answer

Question: Remove Item from Listbox Python, if I do not know the index number


Documentations

  • Python Documentation - Common Sequence Operations

    s.index(x[, i[, j]])    
    index of the first occurrence of x in s (at or after index i and before index j)    
    

    Note: (8) index raises ValueError when x is not found in s. Not all implementations support passing the additional arguments i and j. These arguments allow efficient searching of subsections of the sequence. Passing the extra arguments is roughly equivalent to using s[i:j].index(x), only without copying any data and with the returned index being relative to the start of the sequence rather than the start of the slice.

  • The Tkinter Listbox Widget - get(first, last=None)

    This function returns the string corresponding to the given index (or the strings in the given index range). Use get(0, END) to get a list of all items in the list.


  1. Get the index of a Listbox Item using it's label string

    label = "Shrimp Tempura"
    idx = listbox.get(0, tk.END).index(label)
    
  2. Delete the Listbox Item at this index

    listbox.delete(idx)
    

Tested with Python: 3.5 - TkVersion: 8.6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.