python中自定义事件

python可以响应内部或者预定义的事件:

self.Bind( wx.EVT_PAINT,  self.OnPaint )

def OnPaint( self, evt ):

    # do something here

除此之外,我们开可以自定义事件:


import  wx
import  wx.lib.newevent

MyEvent, EVT_SOME_NEW_EVENT = wx.lib.newevent.NewEvent()
MyCommandEvent, EVT_SOME_NEW_COMMAND_EVENT = wx.lib.newevent.NewCommandEvent()

定义完事件后,就可以预定义事件 一样bind使用了,要发送事件可以

evt = MyEvent()

PostEvent( target, evt )

如果我们想事件中带一些信息,可以这样做:

evt = MyEvent(name=’test’, time=’2012′ )

PostEvent( target, evt )

这样可以在响应事件的时候,把上面设置的参数当做事件的属性访问。

但是非常非常重要的一定千万不要定义Id这个属性,这个属性是预定义好的,是从NewEvent那里继承而来,我们可以测试一下:

>>> import  wx
>>> import  wx.lib.newevent
>>> MyEvent, EVT_SOME_NEW_EVENT = wx.lib.newevent.NewEvent()
>>> e=MyEvent()
>>> dir(e)
[‘ClassName’, ‘Clone’, ‘Destroy’, ‘EventObject’, ‘EventType’, ‘GetClassName’, ‘GetEventObject’, ‘GetEventType’, ‘GetId’, ‘GetSkipped’, ‘GetTimestamp’, ‘Id’, ‘IsCommandEvent’, ‘IsSameAs’, ‘ResumePropagation’, ‘SetEventObject’, ‘SetEventType’, ‘SetId’, ‘SetTimestamp’,
‘ShouldPropagate’, ‘Skip’, ‘Skipped’, ‘StopPropagation’, ‘Timestamp’, ‘_GetSelf’, ‘_SetSelf’, ‘__class__’, ‘__del__’, ‘__delattr__’, ‘__dict__’, ‘__doc__’, ‘__format__’, ‘__getattribute__’, ‘__hash__’, ‘__init__’, ‘__module__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’,
‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘__swig_destroy__’, ‘__weakref__’, ‘this’, ‘thisown’]

看到了吧,Id这个属性已经存在,如果你试图自己定义它的值,如:

evt = MyEvent(name=’test’, time=’2012’,Id=200 )

总是会失败。但是你可以使用SetId()这个方法来设置它的值。

版权所有,禁止转载. 如需转载,请先征得博主的同意,并且表明文章出处,否则按侵权处理.

    分享到:

Leave a Reply

Your email address will not be published. Required fields are marked *