wxPython事件处理

来源:互联网 发布:甬温动车事故 知乎 编辑:程序博客网 时间:2024/06/02 10:42
对事件的反应在wxPython是称为事件处理。一个事件是当“东西”发生在您的应用程序(单击按钮、文本输入、鼠标移动等)。大部分的GUI编程由响应事件。你在绑定对象到事件使用bind()方法:
[python] view plaincopy
  1. class MainWindow(wx.Frame):  
  2.    def __init__(self, parent, title):  
  3.            wx.Frame.__init__(self,parent, title=title, size=(200,100))  
  4.            ...  
  5.            menuItem = filemenu.Append(wx.ID_ABOUT, "&About"," Information about this program")  
  6.            self.Bind(wx.EVT_MENU, self.OnAbout, menuItem)  


This means that, from now on, when the user selects the "About" menu item, the method self.OnAbout will be executed. wx.EVT_MENU is the "select menu item" event. wxWidgets understands many other events (see the full list). The self.OnAbout method has the general declaration:

这是说,从现在开始,当用户选择了"About"按钮,self.OnAbout方法被执行。wx.EVT_MENU代表“选择按钮”事件。wxWidgets明白很多事件处理。

这个方法用下边的形式表现:

[python] view plaincopy
  1. def OnAbout(self, event):  
  2.          ...  
[python] view plaincopy
  1. <span style="font-family:Arial;BACKGROUND-COLOR: #ffffff">这里的event是wx.Event的实例。比如一个按钮单击事件-wx.EVT-BUTTON就是一个wx.Event的实例。</span>  
[python] view plaincopy
  1. def OnButtonClick(self, event):  
  2.        if (some_condition):  
  3.            do_something()  
  4.        else:  
  5.            event.Skip()  
  6.      
  7.    def OnEvent(self, event):  

 

当一个button-click事件发生时,该方法将被调用OnButtonClick。如果some_condition是真的,我们do_something()否则我们让事件处理的更普遍的事件处理程序。现在让我们看看我们的应用程序:
[python] view plaincopy
  1. ''''' 
  2. Created on 2012-6-29 
  3.  
  4. @author: Administrator 
  5. '''  
  6. import wx  
  7.   
  8. class MyFrame(wx.Frame):  
  9.     def __init__(self,parent,title):  
  10.         wx.Frame.__init__(self,parent,title=title,size=(500,250))  
  11.           
  12.         self.contrl = wx.TextCtrl(self,style=wx.TE_MULTILINE)  
  13.           
  14.         self.CreateStatusBar()  
  15.           
  16.         filemenu = wx.Menu()  
  17.         menuAbout=filemenu.Append(wx.ID_ABOUT,"&About","about this program")  
  18.           
  19.         filemenu.AppendSeparator()    
  20.         menuExit=filemenu.Append(wx.ID_EXIT,"E&xit","Close program")    
  21.             
  22.         menuBar = wx.MenuBar()    
  23.         menuBar.Append(filemenu,"&File")   
  24.           
  25.         self.Bind(wx.EVT_MENU, self.OnAbout,menuAbout)  
  26.         self.Bind(wx.EVT_MENU, self.OnExit,menuExit)  
  27.           
  28.            
  29.         self.SetMenuBar(menuBar)    
  30.           
  31.           
  32.         self.Show(True)  
  33.     def OnAbout(self,e):  
  34.         dlg = wx.MessageDialog(self,"A small editor","about simple editor",wx.OK)  
  35.         dlg.ShowModal()  
  36.         dlg.Destroy()  
  37.     def OnExit(self,e):  
  38.         self.Close(True)  
  39.   
  40. app = wx.App(False)  
  41. frame = MyFrame(None,"Small Editor")  
  42. app.MainLoop() 
原创粉丝点击