Search code examples
python-2.7parameterswxpython

wxPython: Passing parameters within GUI class


I am trying to port a CLI based program into a GUI to make it more user friendly. I have got the basics of wxPython, but theres one issue which has stumped me.

I have defined a dialog box which takes a parameter allowing me to create dynamic dialog boxes:

    def infoDialog(self,event,message):
        dialog = wx.MessageDialog(None, message, 'Info', wx.OK | wx.ICON_INFORMATION)
        dialog.ShowModal()

I have a main subroutine within the class which generates all the GUI elements:

    def initGUI(self):
        panel = wx.Panel(self)

If I call the info dialog within initGUI like this:

    pidButton = wx.Button(panel, label='Open...', pos=(540,445), size=(60,20))
    pidButton.Bind(wx.EVT_BUTTON, self.questionDialog(event,"Hi!"))

Then I get this error:

pidButton.Bind(wx.EVT_BUTTON, self.questionDialog(event,"Hi!"))

NameError: global name 'event' is not defined

Yet this works if I call it from a subroutine that isnt initGUI(). How do I go about fixing this?

I appreciate any suggestions


Solution

  • Bind an event handler to the button event, and inside that handler call any actions you would like to happen.

    Notice that when you bind you pass a reference to to the handler without calling it ie no () other wise you bind the result of calling the handler. The handler must accept one argument.

    import wx
    from wx.lib import sized_controls
    
    
    class MainFrame(sized_controls.SizedFrame):
    
        def __init__(self, *args, **kwargs):
            super(MainFrame, self).__init__(*args, **kwargs)
            self.SetTitle('MainFrame')
            pane = self.GetContentsPane()
            button = wx.Button(pane, label='open')
            button.Bind(wx.EVT_BUTTON, self.on_open_button)
    
        def on_open_button(self, event):
            self.infoDialog("Hi!")
    
        def infoDialog(self, message):
            dialog = wx.MessageDialog(
                None, message, 'Info', wx.OK | wx.ICON_INFORMATION)
            dialog.ShowModal()
    
    
    if __name__ == '__main__':
        wxapp = wx.App(False)
        frame = MainFrame(None)
        frame.Show()
        wxapp.MainLoop()