《wxPython in Action》chap 9 筆記
1. Modal Dialog(模式對話框)
A modal dialog blocks other widgets from receiving user events until it is closed;
in other words, it places the user in dialog mode for the duration of its existence.
模式對話框阻塞了別的窗口部件接收用戶事件,直到該模式對話框被關閉。
嚴格來說,dialog 與 frame 在外觀上沒有區別,只是處理事件(event)的方式不一樣。
通常,dialog 在外觀上要稍微簡單一點,所以很少使用 wx.Panel。
wx.Dialog 具備 wx.Panel 的性質,widgets 一般直接添加到 wx.Dialog 中即可。
2. 展示與關閉 Dialog
Modal Dialog 與 普通的 Frame 用法略有差別。
最簡單的示例代碼如下:
import wx class SubclassDialog(wx.Dialog): def __init__(self): wx.Dialog.__init__(self, None, -1, 'Dialog Subclass', size=(300, 100)) okButton = wx.Button(self, wx.ID_OK, "OK", pos=(15, 15)) okButton.SetDefault() cancelButton = wx.Button(self, wx.ID_CANCEL, "Cancel", pos=(115, 15)) if __name__ == '__main__': app = wx.PySimpleApp() dialog = SubclassDialog() result = dialog.ShowModal() if result == wx.ID_OK: print "OK" else: print "Cancel" dialog.Destroy()
2.1 展示 Dialog
展示 Dialog 使用 ShowModal(),程序會等待 ShowModal() 執行結束並獲取其返回值。
此時,Dialog 是 wxPython 應用接受用戶事件的唯一組件。其他應用不受影響。
2.2 結束 Dialog Mode
調用 EndModal(retCode) 方法可以關閉(close)Dialog Mode,retCode 是 int 值,被 ShowModal() 返回。
此時,只是結束了 Dialog Mode,並未摧毀 Dialog。可以在其他地方繼續展示該 Dialog。
通常在 event 的 handler 中調用 EndModal()。
2.3 摧毀 Dialog
調用 Destroy() 方法
2.4 典型用法
dialog = SubclassDialog() result = dialog.ShowModal() # 展示對話框,並等待結果 if result == wx.ID_OK: # 判斷結果,並執行相應處理 print "OK" else: print "Cancel" dialog.Destroy() # 摧毀 Dialog
2.5 自定義 event 的 handler,一般需要調用 EndModal()
例如,用於連接數據庫的 handler 實現如下:
def OnConnect(self, event=None): host = self.input_host.GetValue() port = int(self.input_port.GetValue()) if db.connect(host, port): # connected self.EndModal(wx.ID_OK) else: msg_error = 'Error connecting to host(%s)' % host wx.MessageBox(msg_error, 'Error', wx.OK | wx.ICON_ERROR)