A key component of an event-based system is the process by which an event that comes into the system is dispatched to the piece of code that is executed in response. In this section, we'll walk through the procedure wxPython uses when processing an incoming event. We'll use a small code snippet as an example
Figure 3.2 A simple window with mouse events to trace the steps in the process. Figure 3.2 displays a sample window with a single button, which will be used to generate the sample events.
Listing 3.3 contains the code that generated this window. In this code, wxPython events are generated both by clicking the button and by moving the mouse over the button.
Listing 3.3 Binding multiple kinds of mouse events
#!/usr/bin/env python import wx class MouseEventFrame(wx.Frame):
wx.Frame._init_(self, parent, id, size=(3 00, 100)) self.panel = wx.Panel(self) self.button = wx.Button(self.panel, label="Not Over", pos=(100, 15)) self.Bind(wx.EVT_BUTTON, self.OnButtonClick, self.button) self.button.Bind(wx.EVT_ENTER_WINDOW, self.OnEnterWindow) self.button.Bind(wx.EVT_LEAVE_WINDOW self.OnLeaveWindow)
Frame With Button'
A Bindi Y butto
Binding the button event def OnButtonClick(self, event)
def OnEnterWindow(self, event):
self.button.SetLabel("Over Me!") event.Skip()
<H Binding the r ' C enter event
Binding the mouse d leave event def OnLeaveWindow(self, event):
self.button.SetLabel("Not Over") event.Skip()
frame = MouseEventFrame(parent=None, id=-1)
The MouseEventFrame contains one button in the middle. Clicking on the mouse changes the background color of the frame to green. The mouse click event is bound to the action in line A. When the mouse pointer enters the button, the button caption changes, as bound in line C. When the mouse pointer leaves the button, the caption changes back, as bound in line A.
Looking at the mouse event example raises some questions about event processing in wxPython. In line A, the button event triggered by the button is bound by the frame. How does wxPython know to look for a binding in the frame object, rather than the button object? In lines c and A, the mouse enter and leave events are bound to the button object. Why can't those events also be bound to the frame? Both of these questions are answered by examining the procedure wxPython uses to determine how to respond to an event.
Was this article helpful?