Practical event handling

イベントハンドリングの実習

wxPytohn ではイベントに反応することをイベントハンドリングと呼びます。
柔軟なイベントハンドリングは wxPython の強みのひとつです。
まず基本的なイベントハンドリングを紹介し、後に Advanced Topics で詳細について話します。


イベントは、 wxPython からアプリケーションに送られる「何か」が起こったことを識別するための小さなメッセージです。
ほとんどの場合、イベントと特定のメソッドを関連付けるだけです。
これは擬似メソッドの EVT_* を呼び出すことで実行されます。
たとえば

EVT_MENU(self, ID_ABOUT, self.OnAbout)

これ以降、ウィンドウに送られる ID_ABOUT という ID のメニューを選択した時のイベントは
メソッド self.OnAbout に送られるといえます。
EVT_MENU に渡されるメソッドには一般的な宣言があります

# event は wxEvent のサブクラスです。
def OnAbout(self, event):
    ...

このメソッドがイベントを受け取ったとき、2つの処理が選択できます。

  • イベントをスキップする
  • イベントを受け取って処理するか、(スキップせずに)何もしない

イベントをスキップする場合には event.Skip() を呼び出します。


イベントハンドリングを実装した我々のアプリケーションを見てみましょう。

import os
import wx
ID_ABOUT=101
ID_EXIT=110
class MainWindow(wx.Frame):
    def __init__(self,parent,id,title):
        wx.Frame.__init__(self,parent,wx.ID_ANY, title, size = (200,100))
        self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE)
        self.CreateStatusBar() # A StatusBar in the bottom of the window
        # Setting up the menu.
        filemenu= wx.Menu()
        filemenu.Append(ID_ABOUT, "&About"," Information about this program")
        filemenu.AppendSeparator()
        filemenu.Append(ID_EXIT,"E&xit"," Terminate the program")
        # Creating the menubar.
        menuBar = wx.MenuBar()
        menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar
        self.SetMenuBar(menuBar)  # Adding the MenuBar to the Frame content.
        # ID_ABOUT メニューイベントを self.OnAbout と結び付けます。
        wx.EVT_MENU(self, ID_ABOUT, self.OnAbout) # attach the menu-event ID_ABOUT to the
                                                  # method self.OnAbout
        # ID_EXIT メニューイベントを self.OnExit と結び付けます。
        wx.EVT_MENU(self, ID_EXIT, self.OnExit)   # attach the menu-event ID_EXIT to the
                                                  # method self.OnExit
        self.Show(True)
    def OnAbout(self,e):
        # メッセージダイアログを作成し
        d= wx.MessageDialog( self, " A sample editor \n"
                            " in wxPython","About Sample Editor", wx.OK)
                            # Create a message dialog box
        # モーダル表示して
        d.ShowModal() # Shows it
        # 終わったらダイアログを破棄します。
        d.Destroy() # finally destroy it when finished.
    def OnExit(self,e):
        self.Close(True)  # Close the frame.
app = wx.PySimpleApp()
frame = MainWindow(None, -1, "Sample editor")
app.MainLoop()