wxPython學習筆記
wxPython程序由兩個必要的對象組成,應用對象APP和頂級窗口對象Frame應用程序對象APP管理主事件循環MainLoop()頂級窗口對象Frame管理數據,...
wxPython程序由兩個必要的對象組成,應用對象APP和頂級窗口對象Frame
應用程序對象APP管理主事件循環MainLoop()
頂級窗口對象Frame管理數據,控制并呈現給用戶
先看一段最簡單的代碼:
import wx class App(wx.App):def OnInit(self): frame = wx.Frame(parent = None, title = "Kobe") frame.Show() return True
app = App() app.MainLoop()</pre>
上面的代碼說明了開發wxPython程序必須的5個步驟:
1. 導入wxPython包
2. 子類化wxPython應用類
3. 定義應用程序的初始化方法
4. 創建一個應用程序類的實例
5. 進入這個應用程序的主事件循環(MainLoop())
OnInit()方法沒有參數,返回值為BOOL,此部分可以做一些關鍵數據初始化的動作,如果失敗,返回False,程序退出。通常會在此方法中創建一個Frame對象,并調用Frame的Show()方法。
應用程序對象開始于實例被創建時,結束于最后一個應用程序窗口被關閉,與Python腳本開始執行沒有先后關系。
每個wxPython程序必須有一個application對象和至少一個frame對象。application對象必須是wx.App的一個實例或在OnInit()方法中定義的一個子類的一個實例,當程序啟動時,OnInit()方法將被wx.App父類調用。
上面的代碼中,定義了名為MyApp的子類,在OnInit()方法中創建frame對象。
wx.Frame(self, parent, id, title, pos, size, style, name)其中,只有parent是必須的,其余都有默認值,返回值為空。下面是其各個參數的類型:
parent (type=Window) id (type=int) pos (type=Point) size (type=Size) style (type=long) name (type=String) Returns: bool調用Show()方法使frame可見,否則不可見。可以通過給Show一個布爾值參數來設定frame的可見性:
frame.Show(False) # 框架不可見 frame.Show(True) # 框架可見 frame.Hide() # 等同于frame.Show(False)該程序并沒有定義一個__init__()方法,意味著父方法wx.App.__init()__將在對象創建時被自動調用。若自己定義__init__()方法,還需要調用其基類的__init__()方法。
class App(wx.APP): def __init__(self): wx.APP.__init__(self)如果沒有這樣做, wxPython將不被初始化,并且OnInit()方法也不會調用
當程序進入主循環后,控制權將轉交給wxPython。wxPython GUI程序主要響應用戶的鼠標和鍵盤事件。當一個應用程序的所有框架被關閉后,app.MainLoop()方法將返回,程序退出。
import wx class Frame(wx.Frame):def __init__(self, image, parent=None, id =-1, pos = wx.DefaultPosition, title = "Hello, wxPython!"): temp = image.ConvertToBitmap() size = temp.GetWidth(), temp.GetHeight() wx.Frame.__init__(self, parent, id, title, pos, size) self.bmp = wx.StaticBitmap(parent = self, bitmap = temp)
class App(wx.App):
def OnInit(self): image = wx.Image('wxPython.jpg', wx.BITMAP_TYPE_JPEG) self.frame = Frame(image) self.frame.Show() self.SetTopWindow(self.frame) return True
def main(): app = App() app.MainLoop() if name == 'main': main()</pre></div>