1、背景资料
wxPython API:https://www.wxpython.org/Phoenix/docs/html/
2、入门示例
wxPython最重要的两个概念:App与Frame,其中App只有一个,Frame可以是多个。参见下面代码:
import wx from frame_main import FrameMain class MainApp(wx.App): def __init__(self): wx.App.__init__(self) self.frame = None # 这里声明一下self变量可以避免警告 def OnInit(self): self.frame = FrameMain(None) self.frame.Show(True) return True # 返回False程序将会立即退出 def OnExit(self): self.frame = None # 非必要,只是为了用一下self return 0 # 返回状态码 if __name__ == '__main__': app = MainApp() app.MainLoop()
Frame的设计也比较简单,涉及到多种控件的使用可以专门的研究下,我看表格控件是比较复杂一点的,不过比起C++还是简单很多。
import wx class FrameMain(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent, id=-1, title="Hello World", size=(300, 400)) # 设置窗体 # 状态栏 bar = self.CreateStatusBar() self.SetStatusBar(bar) """ panel和sizer是wxpython提供的窗口部件。是容器部件,可以用于存放其他窗口部件 """ panel = wx.Panel(self) # sizer = wx.BoxSizer(wx.VERTICAL) sizer = wx.GridSizer(rows=3, cols=3, vgap=5, hgap=5) # vgap hgap代表水平距离和垂直距离 panel.SetSizer(sizer) # 创建文本输入框 input_text = wx.TextCtrl(panel, -1, "", pos=(10, 10), size=(150, -1)) input_text.SetInsertionPoint(1) # 设置焦点 # sizer.Add(input_text) # 创建静态文本组件 txt = wx.StaticText(panel, -1, "Hello World!", pos=(10, 50), size=(160, 25), style=wx.ALIGN_CENTER) txt.SetForegroundColour("blue") txt.SetBackgroundColour("green") font = wx.Font(12, wx.DEFAULT, wx.ITALIC, wx.NORMAL, True) # ITALIC倾斜 txt.SetFont(font) # sizer.Add(txt) # 按钮 btn = wx.Button(panel, -1, "Click", pos=(10, 90), size=(80, 30)) # sizer.Add(btn, 0, wx.TOP | wx.LEFT, 50) btn.Bind(wx.EVT_BUTTON, self.OnClick) btn.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseEnter) btn.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseEnter2) btn.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave) # sizer.Add(btn) # 列表控件 color_list = ["红", "绿", "蓝", "白", "紫"] self.listBox = wx.ListBox(panel, -1, pos=(10, 130), size=(80, 110), choices=color_list, style=wx.LB_SINGLE) self.listBox.SetSelection(2) self.Bind(wx.EVT_LISTBOX, self.OnClickList, self.listBox) # sizer.Add(self.listBox) # 表格控件 # self.Center() # 将窗口放在桌面环境的中间 def OnClickList(self, event): index = self.listBox.GetSelection() wx.MessageBox(self.listBox.GetString(index), "提示") def OnClick(self, event): # dialog = wx.Dialog(None, title="Hi, Clicked!", size=(300, 200)) # dialog.Show() #self.Close(True) dialog = wx.TextEntryDialog(None, message="请输入文件名:", caption="文件", value="test") res = dialog.ShowModal() print res def OnMouseEnter(self, event): print "Mouse enter" def OnMouseEnter2(self, event): print "Mouse enter2" event.Skip() # 后注册的事件响应函数会覆盖之前的,默认仅执行一个,如需继续则调用Skip def OnMouseLeave(self, event): print "Mouse leave"
直接看下效果就知道基本框架怎么用了: