[wxPython] How to delete items from ListBox

Hi,
I have ListBox defined with wxLB_EXTENDED option like

self.lb2 = wxListBox(self, 70, wxPoint(280, 50), wxSize(130, 300),
                       sampleList1, wxLB_EXTENDED)

How can I delete items from this ListBox?
I tried the following code but without any success.

          if (self.lb2.GetSelections()!=-1):
            for index2 in self.lb2.GetSelections():
               self.lb2.Delete((index2))

That works only if I choose one item at a time only- If I make a
multiple selection I receive an ivalid index in ListBox::Delete error.

Can you please help.
Thank you
Ladislav

How can I delete items from this ListBox?
I tried the following code but without any success.

          if (self.lb2.GetSelections()!=-1):
            for index2 in self.lb2.GetSelections():
               self.lb2.Delete((index2))

That works only if I choose one item at a time only- If I make a
multiple selection I receive an ivalid index in ListBox::Delete error.

Probably because the indexes are changing when you delete items. If one of
your selected items was closer to the end than the number of items deleted
then it will be an invalid index by the time you get to it. Maybe something
like this:

        selections = list(self.lb2.GetSelections())
        selections.reverse()
        for index in selections:
            self.lb2.Delete(index)

···

--
Robin Dunn
Software Craftsman
robin@AllDunn.com Java give you jitters?
http://wxPython.org Relax with wxPython!

This post is from 2001.

The ListBox widget still seems to have no Clear() method.

Is that still a good way to empty a listbox?

result = wx.MessageBox( "Clear listbox?", "Prompt", style=wx.OK | wx.CANCEL | wx.CANCEL_DEFAULT)
if result == wx.OK:
	for i in range(self.lb1.GetCount()):
		self.lb1.Delete(i)

Perhaps just set its items to an empty list?

import wx

class TestFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title="Clear ListBox Items")
        self.SetSize((300, 400))
        panel = wx.Panel(self)
        sizer = wx.BoxSizer(wx.VERTICAL)
        items = [f"Item {i+1}" for i in range(12)]
        self.list_box = wx.ListBox(panel, choices=items, style=wx.LB_SINGLE)
        sizer.Add(self.list_box, 1, wx.EXPAND, 0)
        clear_button = wx.Button(panel, label="Clear Listbox")
        sizer.Add(clear_button, 0, wx.TOP, 4)
        panel.SetSizer(sizer)
        self.Layout()
        
        clear_button.Bind(wx.EVT_BUTTON, self.OnClear)
        
        
    def OnClear(self, _event):
        self.list_box.SetItems([])


if __name__ == '__main__':
    app = wx.App()
    frame = TestFrame()
    frame.Show()
    app.MainLoop()
1 Like

Even better :slight_smile: Thank you.