2008-10-16

wxPython -- event 範例

這一個範例,是延續之前的範例,但是之前你按下功能表上的選項,並不會有反應!現在就是要讓它有作用!

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.
wx.EVT_MENU(self, ID_ABOUT, self.OnAbout) # attach the menu-event ID_ABOUT to the
# method self.OnAbout
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()

這裡大致上都跟前面沒什麼差別!主要的重點在於這幾行:
wx.EVT_MENU(self, ID_ABOUT, self.OnAbout) # attach the menu-event ID_ABOUT to the
# method self.OnAbout
wx.EVT_MENU(self, ID_EXIT, self.OnExit) # attach the menu-event ID_EXIT to the
# method self.OnExit

而在後面還要去定義OnAbout與OnExit的內容,才能讓滑鼠的動作能對應上我們希望的功能。而在OnAbout裡面我們可以找到如何產生一個Message Dialog Box的語法。
d= wx.MessageDialog( self, " A sample editor \n"
" in wxPython","About Sample Editor", wx.OK)

這樣就會讓我們按下about後,跳出一個對話盒。

沒有留言: