窗口
在wx.Python中使用wx.Frame类表示窗口。窗口是一个包含多个组件的矩形区域,窗口是程序运行后的容器。
Frame窗口
1#!/usr/bin/python
2# -*- coding: UTF-8 -*-
3
4import wx
5
6class MyFrame(wx.Frame):
7 def __init__(self):
8 wx.Frame.__init__(self, None, -1, u'自定义窗口', size=(300, 100)) # 调用父类的初始化方法
9
10if __name__ == '__main__':
11 app = wx.PySimpleApp()
12 myFrame = MyFrame()
13 myFrame.Show()
14 app.MainLoop()
效果:
带工具栏和状态栏的Frame窗口
一个完整的应用程序窗口通常包含菜单、工具栏、状态栏等要素。
1#!/usr/bin/python
2# -*- coding: UTF-8 -*-
3
4import wx
5
6class MyFrame(wx.Frame):
7 def __init__(self):
8 wx.Frame.__init__(self, None, -1, u'自定义窗口', size=(300, 200))
9 png_save = wx.Image('./icons/save_page.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
10 png_home = wx.Image('./icons/go_home.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
11 png_cfg = wx.Image('./icons/settings.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
12 png_forward = wx.Image('./icons/go_forward.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
13 png_back = wx.Image('./icons/go_back.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
14 toolbar = self.CreateToolBar(wx.TB_HORIZONTAL | wx.TB_TEXT) # 创建工具栏
15 toolbar.AddSimpleTool(100, png_save, "Save page")
16 toolbar.AddSimpleTool(200, png_home, "Go home")
17 toolbar.AddSimpleTool(220, png_back, "Go back")
18 toolbar.AddSimpleTool(230, png_forward, "Go Forward")
19 toolbar.AddSimpleTool(400, png_cfg, "Settings")
20 toolbar.Realize()
21 self.CreateStatusBar() # 创建状态栏
22
23if __name__ == '__main__':
24 app = wx.PySimpleApp()
25 myFrame = MyFrame()
26 myFrame.Show()
27 app.MainLoop()
效果:
MDI窗口
给MDI窗口添加菜单,并能够在MDI窗口中创建子窗口
1#!/usr/bin/python
2# -*- coding: UTF-8 -*-
3
4import wx
5
6class MDIFrame(wx.MDIParentFrame):
7 def __init__(self):
8 wx.MDIParentFrame.__init__(self, None, -1, u"MDI窗口", size=(300, 200))
9 menubar = wx.MenuBar() # 添加菜单栏
10 menu = wx.Menu() # 添加菜单
11 menu.Append(5000, u"新建(&N)") # 添加子菜单
12 menu.Append(5001, u"退出(&X)")
13 menubar.Append(menu, u"文件(&F)")
14 self.Bind(wx.EVT_MENU, self.OnNewWindow, id=5000) # 绑定菜单项的事件
15 self.Bind(wx.EVT_MENU, self.OnExit, id=5001)
16 self.SetMenuBar(menubar)
17
18 def OnExit(self, evt):
19 self.Close(True)
20
21 def OnNewWindow(self, evt):
22 win = wx.MDIChildFrame(self, -1, u"子窗口") # 新建子窗口
23 win.Show(True)
24
25if __name__ == '__main__':
26 app = wx.PySimpleApp()
27 frame = MDIFrame()
28 frame.Show()
29 app.MainLoop()
效果:
MiniFrame窗口
1#!/usr/bin/python
2# -*- coding: UTF-8 -*-
3
4import wx
5
6class MiniFrame(wx.MiniFrame):
7 def __init__(self):
8 wx.MiniFrame.__init__(self, None, -1, u'不能最小化和最大化的窗口', pos=(100, 100), size=(300, 200),
9 style=wx.DEFAULT_FRAME_STYLE | wx.CLOSE_BOX)
10 # 或者sytel = wx.DEFAULT_FRAME_STYLE ^ (wx.MINIMIZE_BOX | wx.MAXIMIZE_BOX))
11 panel = wx.Panel(self, -1, size=(300, 200))
12
13if __name__ == '__main__':
14 app = wx.PySimpleApp()
15 frame = MiniFrame()
16 frame.Show()
17 app.MainLoop()
对话框
在wx.Python中对话框都继承自wx.Dialog类。
对话框的创建
1#!/usr/bin/python
2# -*- coding: UTF-8 -*-
3
4import wx
5
6class MyFrame(wx.Frame):
7 def __init__(self):
8 wx.Frame.__init__(self, None, -1, u"自定义对话框", size=(300, 200))
9 MenuHelp = wx.Menu()
10 aboutMenu = MenuHelp.Append(-1, u"关于(&A)")
11 menuBar = wx.MenuBar()
12 menuBar.Append(MenuHelp, u"帮助(&H)")
13 self.Bind(wx.EVT_TOOL, self.ShowAboutDlg, aboutMenu)
14 self.SetMenuBar(menuBar)
15
16 def ShowAboutDlg(self, event):
17 pos = self.GetPosition()
18 dialog = MyDialog(self, -1, u"关于")
19 dialog.SetPosition((pos[0] + 100, pos[1] + 60))
20
21class MyDialog(wx.Dialog):
22 def __init__(self, parent, id, title):
23 wx.Dialog.__init__(self, parent, id, title, size=(100, 100))
24 self.panel = wx.Panel(self)
25 self.OkBtn = wx.Button(self, 10, u"确定", pos=(8, 20), size=(80, 30))
26 self.Bind(wx.EVT_BUTTON, self.CloseDlg, self.OkBtn)
27 self.Show()
28 # self.ShowModal()
29
30 def CloseDlg(self, event):
31 self.Close()
32
33if __name__ == '__main__':
34 app = wx.PySimpleApp()
35 frame = MyFrame()
36 frame.Show()
37 app.MainLoop()
效果:
提示对话框
1#!/usr/bin/python
2# -*- coding: UTF-8 -*-
3
4import wx
5
6class MyFrame(wx.Frame):
7 def __init__(self):
8 wx.Frame.__init__(self, None, -1, u"对话框", size=(300, 100))
9 button = wx.Button(self, wx.ID_OK, u"退出", pos=(10, 10))
10 button.SetDefault()
11 self.Bind(wx.EVT_BUTTON, self.OnClick, button)
12
13 def OnClick(self, event):
14 # 创建选择对话框
15 dlg = wx.MessageDialog(None, u"是否退出?", u"退出", wx.YES_NO | wx.ICON_QUESTION)
16 # 判断用户选择的返回值
17 if (dlg.ShowModal() == wx.ID_YES):
18 frame.Close()
19 dlg.Destroy()
20
21if __name__ == '__main__':
22 app = wx.PySimpleApp()
23 frame = MyFrame()
24 frame.Show()
25 app.MainLoop()
效果:
文本输入对话框
1#!/usr/bin/python
2# -*- coding: UTF-8 -*-
3
4import wx
5
6class MyFrame(wx.Frame):
7 def __init__(self):
8 wx.Frame.__init__(self, None, -1, "TextEntryDialog", size=(300, 100))
9 panel = wx.Panel(self, -1)
10 self.textCtrl = wx.TextCtrl(panel, -1, "", pos=(10, 10), style=wx.TE_PROCESS_ENTER)
11 self.textCtrl.Bind(wx.EVT_TEXT_ENTER, self.OnClick, self.textCtrl)
12
13 def OnClick(self, evt):
14 # 创建文本对话框
15 self.dialog = wx.TextEntryDialog(None, u"输入文本", u"文本对话框", "", style=wx.OK | wx.CANCEL)
16 if self.dialog.ShowModal() == wx.ID_OK:
17 self.textCtrl.SetLabel(self.dialog.GetValue()) # 获取输入文本的内容
18
19if __name__ == "__main__":
20 app = wx.PySimpleApp()
21 frame = MyFrame()
22 frame.Show()
23 app.MainLoop()
效果:
特殊对话框
包括文件打开对话框、字体对话框、颜色选择对话框等\
打开文件对话框由wx.FileDialog类创建,构造函数如下:
1#!/usr/bin/python
2# -*- coding: UTF-8 -*-
3
4import wx
5import os
6
7def ShowFileDialog():
8 filterFile = "Python source (*.py)|*.py| All files (*.*)|*.*" # 过滤文件
9 dialog = wx.FileDialog(None, u"选择文件", os.getcwd(), "", filterFile, wx.OPEN)
10 dialog.ShowModal()
11 dialog.Destroy()
12
13if __name__ == "__main__":
14 app = wx.PySimpleApp()
15 ShowFileDialog()
效果:
窗口和对话框的交互
1#!/usr/bin/python
2# -*- coding: UTF-8 -*-
3
4import wx
5
6class MyFrame(wx.Frame):
7 def __init__(self):
8 wx.Frame.__init__(self, None, -1, u"对话框的验证", size=(300, 60))
9 panel = wx.Panel(self, -1)
10 sizer = wx.BoxSizer(wx.HORIZONTAL)
11 self.addTextCtrl = wx.TextCtrl(panel, -1, "", pos=(10, 10))
12 addStaticText = wx.StaticText(panel, -1, "+")
13 self.addTextCtrl2 = wx.TextCtrl(panel, -1, "")
14 btn = wx.Button(panel, -1, u"计算")
15 btn.Bind(wx.EVT_BUTTON, self.OnClick, btn)
16 sizer.Add(self.addTextCtrl)
17 sizer.Add(addStaticText)
18 sizer.Add(self.addTextCtrl2)
19 sizer.Add(btn)
20 panel.SetSizer(sizer)
21 panel.Fit()
22
23 def OnClick(self, event):
24 data = {0: self.addTextCtrl.GetValue(), 1: self.addTextCtrl2.GetValue()}
25 dlg = MyDialog(data)
26 dlg.ShowModal()
27 dlg.Destroy()
28
29class DataValidator(wx.PyValidator): # 对话框的验证器
30 def __init__(self, data, key):
31 wx.PyValidator.__init__(self)
32 self.data = data
33 self.key = key
34
35 def Clone(self): # Clone()方法必须实现
36 return DataValidator(self.data, self.key)
37
38 def Validate(self, win): # 验证数据
39 return True
40
41 def TransferToWindow(self): # 对话框打开时调用
42 textCtrl = self.GetWindow()
43 textCtrl.SetValue(self.data.get(self.key, ""))
44 return True
45
46 def TransferFromWindow(self): # 对话框关闭时调用
47 return True
48
49class MyDialog(wx.Dialog):
50 def __init__(self, data):
51 wx.Dialog.__init__(self, None, -1, u"验证器")
52 addStaticText = wx.StaticText(self, -1, u"数字1:")
53 addStaticText2 = wx.StaticText(self, -1, u"数字2:")
54 self.addTextCtrl = wx.TextCtrl(self, validator=DataValidator(data, 0)) # 添加验证
55 self.addTextCtrl2 = wx.TextCtrl(self, validator=DataValidator(data, 1))
56 btn = wx.Button(self, wx.ID_OK, u"确定")
57 btn.Bind(wx.EVT_BUTTON, self.OnClick, btn)
58 btn.SetDefault()
59 sizer = wx.BoxSizer(wx.VERTICAL)
60 gridSizer = wx.FlexGridSizer(2, 2, 5, 5)
61 gridSizer.Add(addStaticText, 0, wx.ALIGN_LEFT)
62 gridSizer.Add(self.addTextCtrl, 0, wx.EXPAND)
63 gridSizer.Add(addStaticText2, 0, wx.ALIGN_LEFT)
64 gridSizer.Add(self.addTextCtrl2, 0, wx.EXPAND)
65 sizer.Add(gridSizer, 0, wx.EXPAND | wx.ALL, 5)
66 sizer.Add(btn, 0, 5)
67 self.SetSizer(sizer)
68 sizer.Fit(self)
69
70 def OnClick(self, event):
71 result = float(self.addTextCtrl.GetValue()) + float(self.addTextCtrl2.GetValue())
72 wx.MessageBox(str(result), u"结果")
73 self.Close()
74
75if __name__ == '__main__':
76 app = wx.PySimpleApp()
77 frame = MyFrame()
78 frame.Show()
79 app.MainLoop()
效果:
wxPython库中的高级功能
剪贴板的操作
剪贴板是在各个应用之间交换数据的一种方式,一个应用程序可以将数据保存在剪贴板上,另外一个应用程序可以从剪贴板中获取数据。保存在剪贴板的数据可以是文本、图像或者是其他的文件对象等。
wxPython中的剪贴板对象
处理剪贴板对象
1#!/usr/bin/python
2# -*- coding: UTF-8 -*-
3
4import wx
5from wx import xrc
6
7class MyApp(wx.App):
8 def OnInit(self):
9 self.res = xrc.XmlResource('clipboard.xrc') # 从XRC文件中读取界面描述
10 self.init_frame()
11 return True
12
13 def init_frame(self):
14 self.frame = self.res.LoadFrame(None, 'MyFrame2')
15 self.panel = xrc.XRCCTRL(self.frame, 'm_Panel1')
16 self.text1 = xrc.XRCCTRL(self.panel, 'm_textCtrl4')
17 self.text2 = xrc.XRCCTRL(self.panel, 'm_textCtrl5')
18 self.frame.Bind(wx.EVT_BUTTON, self.OnCopy, id=xrc.XRCID('m_button6')) # 绑定事件
19 self.frame.Bind(wx.EVT_BUTTON, self.OnPaste, id=xrc.XRCID('m_button7')) # 绑定事件
20 self.frame.Bind(wx.EVT_BUTTON, self.OnQuit, id=xrc.XRCID('m_button8')) # 绑定事件
21 self.frame.Show()
22
23 def OnQuit(self, event):
24 self.frame.Close(True)
25
26 def OnCopy(self, event): # 复制数据到剪贴板中
27 data = wx.TextDataObject()
28 data.SetText(self.text1.GetValue())
29 if wx.TheClipboard.Open():
30 wx.TheClipboard.SetData(data)
31 wx.TheClipboard.Close()
32 else:
33 wx.MessageBox("不能打开剪贴板", "错误")
34
35 def OnPaste(self, event): # 从剪贴板中读取数据
36 data = wx.TextDataObject()
37 success = False
38 if wx.TheClipboard.Open():
39 success = wx.TheClipboard.GetData(data)
40 wx.TheClipboard.Close()
41 else:
42 wx.MessageBox("不能打开剪贴板", "错误")
43
44 if success:
45 self.text2.SetValue(data.GetText())
46 else:
47 wx.MessageBox("格式不匹配", "错误")
48
49if __name__ == '__main__':
50 app = MyApp(False)
51 app.MainLoop()
官方Demo研究
下载 wxPython3.0-win32-docs-demos-3.0.0.0.exe 安装
安装后进入 wxPython3.0 Docs and Demos\demo 所在目录,可以看到很多官方写的demo
运行方式:python run.py CheckBox.py
运行说明:python 命令运行 run.py 脚本,而run.py脚本带有参数,该参数指向一个脚本文件,使用run.py脚本运行另外一个脚本。
更多Python技术干货欢迎前往公众号【Python编程学习圈】了解,内容详细丰富,还有大量系统化学习资料以及教程可以免费获取,不要错过啦!