Search code examples
drop-down-menuevent-handlingwxwidgetswxpython

wxPython: wx.Choice event EVT_CHOICE fires on app start but not on selection change


I create a wx.Choice using the following class:

class LanguageSelector(wx.Choice):
"""Class for the creation of a language selector."""
def __init__(self, parent):
    """Create a language selector, default to current language and bind options to localisation methods."""
    super().__init__(parent=parent, choices=self.list_available_languages())

    self.SetSelection(self.FindString(loc.o))  # Set current language as default option.

    self.Bind(wx.EVT_CHOICE, self.on_choice())  # This is the problem.

def on_choice(self):
    print("on_choice was triggered. Selected item is: " + str(self.GetSelection()))
    selection = self.GetString(self.GetSelection())
    print("Converted selection is: " + selection)
    loc.change(selection)

Don't mind the "loc" item: it's something I use to handle localisation.
self.list_available_languages() is a static method that populates the Choice with items.

Now the problem: when I run the app, the print messages are printed immediately and show the default selection (which is something that I'd rather didn't happen, but it's not important), but then no event is ever fired when I try to select the various options in the Choice drop-down, regardless of which one I choose.

I'd prefer not having to use a button to catch the selection and do it right when the selection is changed. I don't understand what I'm doing wrong.


Solution

  • You're invoking your handler instead of binding it. You must pass the function and not the result of calling this function to Bind(). Just remove the parentheses to fix this.