5.3 Practical event handling

Reacting to events in wxPython is called event handling. Flexible event handling is one of the biggest strengths of wxPython. We are going to present practical basic event handling and we'll discuss later in advanced topics, the why and how. An event is a small message sent by wxPython to your application to signify that "something" has happened 6. Most often, in wxPython, all you have to do, is to "connect" an event with a particular method. This is done by calling the pseudo methods EVT_*. By instance:
EVT_MENU(self, ID_ABOUT, self.OnAbout )
In other words, from now on, any menu selection event with ID, ID_ABOUT that is sent to window self, will be passed to the method self.OnAbout. The latter method has the general declaration:
def OnAbout(self, event):
	...
where event is an instance of a subclass of wxEvent. Let's now have a look at what it is like in our application:
from wxPython.wx import *
ID_ABOUT=101
ID_EXIT=110
class MainWindow(wxFrame):
    def __init__(self,parent,id,title):
        wxFrame.__init__(self,parent,-4, title, size = ( 200,100),                    					
   					style=wxDEFAULT_FRAME_STYLE|
               				wxNO_FULL_REPAINT_ON_RESIZE)
        self.control = wxTextCtrl(self, 1, style=wxTE_MULTILINE)
        self.CreateStatusBar() # A Statusbar in the bottom of the window
        # Setting up the menu.
        filemenu= wxMenu()
        filemenu.Append(ID_ABOUT, "&About"," Information about this program")
        filemenu.AppendSeparator()
        filemenu.Append(ID_EXIT,"E&xit"," Terminate the program")
        # Creating the menubar.
        menuBar = wxMenuBar()
        menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar
        self.SetMenuBar(menuBar)  # Adding the MenuBar to the Frame content.
        EVT_MENU(self, ID_ABOUT, self.OnAbout) # attach the menu-event ID_ABOUT to the 
        						   # method self.OnAbout
        EVT_MENU(self, ID_EXIT, self.OnExit)   # attach the menu-event ID_EXIT to the
        						   # method self.OnExit
        self.Show(true)
    def OnAbout(self,e):
        d= wxMessageDialog( self, " A sample editor \n"
                            " in wxPython","About Sample Editor", wxOK)  
                            # Create a message dialog box
        d.ShowModal() # Shows it
        d.Destroy() # finally destroy it when finished.
    def OnExit(self,e):
        self.Close(true)  # Close the frame.
app = wxPySimpleApp()
frame = MainWindow(None, -1, "Sample editor")
frame.Show(1)
app.MainLoop()


Footnotes

... happened6
the mouse has been moved, a key has been pressed, the user has popped up the menu, everything you might possibly think of...