Search code examples
pythonwxpython

Fastest way to populate wx.Choice?


Need to populate a wx.Choice with hundreds of choices, and it looks like there's only one method for this, which is Append():

choiceBox = wx.Choice(choices=[], id = wx.ID_ANY, parent=self, pos=wx.Point(0, 289),
                                          size=wx.Size(190, 21), style=0)

for item in aList:
    choiceBox.Append(item)

I've tried to append a whole list all at once but it won't work, so is there any better way to do this?


Solution

  • what ??? you just give it to choices

    choiceBox = wx.Choice(choices=aList, id = wx.ID_ANY, parent=self, pos=wx.Point(0, 289),
                                          size=wx.Size(190, 21), style=0)
    

    you can also do it later with

    choicebox.SetItems(aList)
    

    here is a simple example where generating the choices takes a long time , but we use threading to not block the ui

    import wx
    import threading 
    import time
    import random
    def make_choices():
        choices = []
        for _ in range(80):
            choices.append(str(random.randint(0,1000000)))
            time.sleep(0.1)
            print "Making choice List!"
        return choices
    
    def make_choice_thread(wxChoice,choice_fn):
        wx.CallAfter(wxChoice.SetItems,choice_fn())
        wx.CallAfter(wxChoice.SetSelection,0)
    
    a = wx.App(redirect=False)
    fr = wx.Frame(None,-1,"A Big Choice...")
    st = wx.StaticText(fr,-1,"For Some reason you must pick from a large list")
    ch = wx.Choice(fr,-1,choices=["Loading...please wait!"],size=(200,-1),pos=(15,15))
    ch.SetSelection(0)
    t = threading.Thread(target=make_choice_thread,args=(ch,make_choices))
    t.start()
    fr.Show()
    a.MainLoop()