Getting selected items from a ListCtrl in wxPython
I seem to be on a roll with getting selected items from various wxPython controls.
This time, I needed to get the selected items from a list control. wx.ListCtrl doesn't have a simple method for getting the selection, but building on this post by Robin Dunn, I was able to cobble my own together using the GetNextItem method.
The get_selected_items function below will return a list of selected indices for list_control. Naturally, you could make these methods of a class derived from wx.ListCtrl if that's how you roll.
"""
Gets the selected items for the list control.
Selection is returned as a list of selected indices,
low to high.
"""
selection = []
# start at -1 to get the first selected item
current = -1
while True:
next = GetNextSelected(list_control, current)
if next == -1:
return selection
selection.append(next)
current = next
def GetNextSelected(list_control, current):
"""Returns next selected item, or -1 when no more"""
return list_control.GetNextItem(current,
wx.LIST_NEXT_ALL,
wx.LIST_STATE_SELECTED)

Thnx, this was what I’m looking for.
Hi, I have modify it.
GetNextSelected (and other usefull functions) is already built-in for wx.ListCtrl in wxPython (at least since 2.8.9.1):
def GetSelectedItems(listCtrl): """ Gets the selected items for the list control. Selection is returned as a list of selected indices, low to high. """ selection = [] index = listCtrl.GetFirstSelected() selection.append(index) while len(selection) != listCtrl.GetSelectedItemCount(): index = listCtrl.GetNextSelected(index) selection.append(index) return selectionAny Idea how to get this selection only once, cause wx.EVT_LIST_ITEM_SELECTED fire for every selected Item, so I get sequence of selections, like:
(0,)
(0, 1)
(0, 1, 2)
(0, 1, 2, 3)
(0, 1, 2, 3, 4)
What is Your best practice to get only least sequence (0, 1, 2, 3, 4)?
If GetNextSelected is a free-standing function, it shouldn’t matter if there’s a method by that name on the list control. My method still works with the latest version of wxPython, so I’d recommend sticking with that.
You are right! Furthermore, I’m sure that this is exactly same implementation inside wxPy.
Is this method still advisable in the latest versions of WxPython? I’m looking into this matter for a project I’m working on and I’m having some difficulty deciding if I should research workaround solutions or if there is an “official” solution to this.
Thanks!
@Jeff
As far as I know, you’ve still got to use a similar workaround, although more recent versions of WxPython do have a ListCtrl.GetNextSelected method, so you don’t need to write that yourself.