如何从我自己的代码中手动调用特定事件?
最佳答案
老话题,但我想我在困惑了很长时间后已经弄清楚了,所以如果其他人来这里寻找答案,这可能会有所帮助。
要手动发布事件,您可以使用
self.GetEventHandler().ProcessEvent(event)
(wxWidgets 文档 here , wxPython 文档 here )
或
wx.PostEvent(self.GetEventHandler(), event)
( wxWidgets docs , wxPython docs )
其中 event
是您要发布的事件。用例如构造事件
wx.PyCommandEvent(wx.EVT_BUTTON.typeId, self.GetId())
如果您想发布 EVT_BUTTON 事件。使它成为 PyCommandEvent意味着它会向上传播;其他事件类型默认不传播。
您还可以创建自定义事件来携带您想要的任何数据。这是一个例子:
myEVT_CUSTOM = wx.NewEventType()
EVT_CUSTOM = wx.PyEventBinder(myEVT_CUSTOM, 1)
class MyEvent(wx.PyCommandEvent):
def __init__(self, evtType, id):
wx.PyCommandEvent.__init__(self, evtType, id)
myVal = None
def SetMyVal(self, val):
self.myVal = val
def GetMyVal(self):
return self.myVal
(我想我在某处的邮件列表存档中找到了此代码,但我似乎无法再次找到它。如果这是您的示例,谢谢!请添加评论并感谢它!)
现在,发布自定义事件:
event = MyEvent(myEVT_CUSTOM, self.GetId())
event.SetMyVal('here is some custom data')
self.GetEventHandler().ProcessEvent(event)
您可以像绑定(bind)任何其他事件一样绑定(bind)它
self.Bind(EVT_CUSTOM, self.on_event)
并在事件处理程序中获取自定义数据
def on_event(self, e):
data = e.GetMyVal()
print 'custom data is: {0}'.format(data)
或者在事件构造函数中包含自定义数据并保存一个步骤:
class MyEvent(wx.PyCommandEvent):
def __init__(self, evtType, id, val = None):
wx.PyCommandEvent.__init__(self, evtType, id)
self.myVal = val
等等
希望这对某人有所帮助。
关于python - wxPython:手动调用事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/747781/