イベントに関して
- イベントは、イベントクラスとイベントタイプの2つにより、どのイベントかを区別できる。
- イベントは、wx.Eventクラスのサブクラスとして表現される。例えば、wx.MouseEventクラスなど。
- イベントタイプは、wx.EventクラスのGetEventType()メソッドで取得できる。
- イベントタイプは、wx.EventBinderクラスのインスタンスで、wx.EVT_*としてあらかじめ定義されている。例えば、wx.MouseEventのイベントタイプのwx.EVT_LEFT_DOWNなど。
- イベントのバインドは、wx.EvtHandlerクラスのBind()メソッドで行う。
- wxPythonの全てのwidgetはwx.EvtHandlerのサブクラス。例えば、wx.Frameクラスなど。
- Bindのシグネチャは以下の通り。Bind(event, handler, source=None, id=wx.ID_ANY, id2=wx.ID_ANY)
- event引数は、wx.PyEventBinderのインスタンスを指定する。handler引数は、イベントを1つ引数にとる実行する関数やメソッドを指定する。
- handlerにNoneを指定すると、イベントの対応付けをなくすことができる。
- source引数は、イベントを発生元のwidgetを指定する。例えば、self.Bind(wx.EVT_BUTTON, self.OnClick, button)など。
サンプル
- 以下、ボタンをクリックするとボタンのラベルに'Clicked'と表示するサンプル。
import wx
class MouseEventFrame(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id, 'Frame with Button', size=(300, 100))
self.panel = wx.Panel(self)
self.button = wx.Button(self.panel, label='Click', pos=(100, 15))
self.Bind(wx.EVT_BUTTON, self.OnButtonClick, self.button)
def OnButtonClick(self, event):
self.button.SetLabel('Clicked!')
if __name__ == '__main__':
app = wx.PySimpleApp()
frame = MouseEventFrame(parent=None, id=-1)
frame.Show()
app.MainLoop()