出处:http://www.cnblogs.com/coderzh/archive/2008/11/23/1339310.html
一、简介
wxPython是Python编程语言的一个GUI工具箱。他使得Python程序员能够轻松的创建具有健壮、功能强大的图形用户界面的程序。它是Python语言对流行的wxWidgets跨平台GUI工具库的绑定。而wxWidgets是用C++语言写成的。和Python语言与wxWidgets GUI工具库一样,wxPython是开源软件。这意味着任何人都可以免费地使用它并且可以查看和修改它的源代码,或者贡献补丁,增加功能。wxPython是跨平台的。这意味着同一个程序可以不经修改地在多种平台上运行。现今支持的平台有:32位微软Windows操作系统、大多数Unix或类Unix系统、苹果Mac OS X。由于使用Python作为编程语言,wxPython编写简单、易于理解。
二、基本使用
基本使用的话到这个地址看已经很详细了,我没有必要重复一遍啦:
http://wiki.wxpython.org/Getting%20Started
三、常用控件
1. 菜单(menu)
http://wiki.wxpython.org/Getting%20Started#head-33e6dc36df2a89db146142e9a97b6e36b956875f
2. 页面布局(Sizer)
这个东东使用起来比较麻烦,参考以下页面吧:
http://wiki.wxpython.org/Getting%20Started#head-7455553d71be4fad208480dffd53b7c68da1a982
wxPython frame的布局详细解释(一)
wxPython frame的布局详细解释(二)
3. Tab页面(notebook)
http://wiki.wxpython.org/Getting%20Started#head-b20d2fc488722cdb3f6193150293d1e118734db8
4. 列表控件(ListCtrl)
这个控件比较强大,是我比较喜欢使用的控件之一。在《wxPythonInAction》一书中第13章有介绍(想要该书电子版及附带源码的朋友可以问我要)
下面是list_report.py中提供的简单用法:
import wx
import sys, glob, random
import data
class DemoFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1,
"wx.ListCtrl in wx.LC_REPORT mode",
size=(600,400))
il = wx.ImageList(16,16, True)
for name in glob.glob("smicon??.png"):
bmp = wx.Bitmap(name, wx.BITMAP_TYPE_PNG)
il_max = il.Add(bmp)
self.list = wx.ListCtrl(self, -1, style=wx.LC_REPORT)
self.list.AssignImageList(il, wx.IMAGE_LIST_SMALL)
# Add some columns
for col, text in enumerate(data.columns):
self.list.InsertColumn(col, text)
# add the rows
for item in data.rows:
index = self.list.InsertStringItem(sys.maxint, item[0])
for col, text in enumerate(item[1:]):
self.list.SetStringItem(index, col+1, text)
# give each item a random image
img = random.randint(0, il_max)
self.list.SetItemImage(index, img, img)
# set the width of the columns in various ways
self.list.SetColumnWidth(0, 120)
self.list.SetColumnWidth(1, wx.LIST_AUTOSIZE)
self.list.SetColumnWidth(2, wx.LIST_AUTOSIZE)
self.list.SetColumnWidth(3, wx.LIST_AUTOSIZE_USEHEADER)
app = wx.PySimpleApp()
frame = DemoFrame()
frame.Show()
app.MainLoop()
对于ListCtrl控件,我要补充的几个地方是:
1. 如何获取选中的项目?
最常用的方法就是获取选中的第一项:GetFirstSelected(),这个函数返回一个int,即ListCtrl中的项(Item)的ID。
还有一个方法是:GetNextSelected(itemid),获取指定的itemid之后的第一个被选中的项,同样也是返回itemid。
通过这两个方法,我们就可以遍历所有选中的项了:
itemid = self.list.GetFirstSelected()
while itemid <> -1:
#Do something
itemid = self.list.GetNextSelected(itemid)
如果要获取某一行,某一列的值,则通过下面的方法:
#
获取第0行,第1列的值
itemtext
=
self.list.GetItem(0,
1
).Text
2. 如何在选定项后添加右键菜单?
在__init__函数中,添加如下的事件绑定:
self.list.Bind(wx.EVT_CONTEXT_MENU, self.OnContextMenu)
然后,添加OnContextMenu方法:
def OnContextMenu(self, event):
if not hasattr(self, "popupStop"):
self.popupStop = wx.NewId()
self.popupPropery = wx.NewId()
self.Bind(wx.EVT_MENU, self.OnPopupStop, id = self.popupStop)
self.Bind(wx.EVT_MENU, self.OnPopupProperty, id = self.popupPropery)
# 创建菜单
menu = wx.Menu()
itemStop = wx.MenuItem(menu, self.popupStop, "Stop")
itemProperty = wx.MenuItem(menu, self.popupPropery, 'Property')
menu.AppendItem(itemStop)
menu.AppendItem(itemProperty)
itemProperty.Enable(False)#默认让属性按钮变成无效状态
if itemid == -1:#如果没有选中任何项
itemStop.Enable(False)
else:
itemStop.Enable(False)
itemProperty.Enable(True)
#到这里才弹出菜单
self.PopupMenu(menu)
#最后注意销毁前面创建的菜单
menu.Destroy()
5. 选择文件对话框(FileDialog)
使用起来非常简单:
dlg = wx.FileDialog(self,
message="Yes, select a place ",
wildcard="PNG(*.png)|*.png" ,
style=wx.SAVE
)
savefile = ''
if dlg.ShowModal() == wx.ID_OK:
savefile = dlg.GetPath()
try:
os.remove(self.filename)
except:
pass
self.img.SaveFile(savefile, wx.BITMAP_TYPE_PNG)
self.filename = savefile
dlg.Destroy()
6. 选择文件夹对话框(DirDialog)
dialog = wx.DirDialog(None, 'Choose a directory: ',
style = wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
if dialog.ShowModal() == wx.ID_OK:
for itemid in range(self.list.GetItemCount()):
self.savechart(itemid, graphpath)
dialog.Destroy()
四、一些技巧
1. 设置快捷键
比如,希望按F5执行某个操作,可以在__init__函数中使用如下方法:
acceltbl
=
wx.AcceleratorTable([(wx.ACCEL_NORMAL, wx.WXK_F5, self.btnrun.GetId())])
self.SetAcceleratorTable(acceltbl)
还有一种很常用的情况,就是按ESC键关闭窗口。我们知道,有一种非常简单的办法就是使用SetId(wx.ID_CANCEL)方法,如:
self.btncancel
=
wx.Button(self.panel1,
-
1
,
'
Cancel
'
, wx.Point(
380
,
280
))
self.btncancel.SetId(wx.ID_CANCEL)
这样,按ESC键时,将会关闭当前Dialog,注意!这里是说Dialog,即继承自wx.Dialog的窗口对象,对于wx.Frame使用SetId似乎没有效果。
2. 使用定时器timer
在《wxPythonInAction》18章有个例子,如下:
import wx
import time
class ClockWindow(wx.Window):
def __init__(self, parent):
wx.Window.__init__(self, parent)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
self.timer.Start(1000)
def Draw(self, dc):
t = time.localtime(time.time())
st = time.strftime("%I:%M:%S", t)
w, h = self.GetClientSize()
dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
dc.Clear()
dc.SetFont(wx.Font(30, wx.SWISS, wx.NORMAL, wx.NORMAL))
tw, th = dc.GetTextExtent(st)
dc.DrawText(st, (w-tw)/2, (h)/2 - th/2)
def OnTimer(self, evt):
dc = wx.BufferedDC(wx.ClientDC(self))
self.Draw(dc)
def OnPaint(self, evt):
dc = wx.BufferedPaintDC(self)
self.Draw(dc)
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="wx.Timer")
ClockWindow(self)
app = wx.PySimpleApp()
frm = MyFrame()
frm.Show()
app.MainLoop()
3. 使用多线程时你必须知道的:wx.CallAfter
在wxpython中编写多线程案例时特别需要注意,线程中通知窗口对象更新状态时,必须使用wx.CallAfter。同样是18章的例子:
import wx
import threading
import random
class WorkerThread(threading.Thread):
"""
This just simulates some long-running task that periodically sends
a message to the GUI thread.
"""
def __init__(self, threadNum, window):
threading.Thread.__init__(self)
self.threadNum = threadNum
self.window = window
self.timeToQuit =<
import wx
import sys, glob, random
import data
class DemoFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1,
"wx.ListCtrl in wx.LC_REPORT mode",
size=(600,400))
il = wx.ImageList(16,16, True)
for name in glob.glob("smicon??.png"):
bmp = wx.Bitmap(name, wx.BITMAP_TYPE_PNG)
il_max = il.Add(bmp)
self.list = wx.ListCtrl(self, -1, style=wx.LC_REPORT)
self.list.AssignImageList(il, wx.IMAGE_LIST_SMALL)
# Add some columns
for col, text in enumerate(data.columns):
self.list.InsertColumn(col, text)
# add the rows
for item in data.rows:
index = self.list.InsertStringItem(sys.maxint, item[0])
for col, text in enumerate(item[1:]):
self.list.SetStringItem(index, col+1, text)
# give each item a random image
img = random.randint(0, il_max)
self.list.SetItemImage(index, img, img)
# set the width of the columns in various ways
self.list.SetColumnWidth(0, 120)
self.list.SetColumnWidth(1, wx.LIST_AUTOSIZE)
self.list.SetColumnWidth(2, wx.LIST_AUTOSIZE)
self.list.SetColumnWidth(3, wx.LIST_AUTOSIZE_USEHEADER)
app = wx.PySimpleApp()
frame = DemoFrame()
frame.Show()
app.MainLoop()
while itemid <> -1:
#Do something
itemid = self.list.GetNextSelected(itemid)
itemtext = self.list.GetItem(0, 1 ).Text
def OnContextMenu(self, event):
if not hasattr(self, "popupStop"):
self.popupStop = wx.NewId()
self.popupPropery = wx.NewId()
self.Bind(wx.EVT_MENU, self.OnPopupStop, id = self.popupStop)
self.Bind(wx.EVT_MENU, self.OnPopupProperty, id = self.popupPropery)
# 创建菜单
menu = wx.Menu()
itemStop = wx.MenuItem(menu, self.popupStop, "Stop")
itemProperty = wx.MenuItem(menu, self.popupPropery, 'Property')
menu.AppendItem(itemStop)
menu.AppendItem(itemProperty)
itemProperty.Enable(False)#默认让属性按钮变成无效状态
if itemid == -1:#如果没有选中任何项
itemStop.Enable(False)
else:
itemStop.Enable(False)
itemProperty.Enable(True)
#到这里才弹出菜单
self.PopupMenu(menu)
#最后注意销毁前面创建的菜单
menu.Destroy()
dlg = wx.FileDialog(self,
message="Yes, select a place ",
wildcard="PNG(*.png)|*.png" ,
style=wx.SAVE
)
savefile = ''
if dlg.ShowModal() == wx.ID_OK:
savefile = dlg.GetPath()
try:
os.remove(self.filename)
except:
pass
self.img.SaveFile(savefile, wx.BITMAP_TYPE_PNG)
self.filename = savefile
dlg.Destroy()
dialog = wx.DirDialog(None, 'Choose a directory: ',
style = wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
if dialog.ShowModal() == wx.ID_OK:
for itemid in range(self.list.GetItemCount()):
self.savechart(itemid, graphpath)
dialog.Destroy()
self.SetAcceleratorTable(acceltbl)
self.btncancel.SetId(wx.ID_CANCEL)
import wx
import time
class ClockWindow(wx.Window):
def __init__(self, parent):
wx.Window.__init__(self, parent)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
self.timer.Start(1000)
def Draw(self, dc):
t = time.localtime(time.time())
st = time.strftime("%I:%M:%S", t)
w, h = self.GetClientSize()
dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
dc.Clear()
dc.SetFont(wx.Font(30, wx.SWISS, wx.NORMAL, wx.NORMAL))
tw, th = dc.GetTextExtent(st)
dc.DrawText(st, (w-tw)/2, (h)/2 - th/2)
def OnTimer(self, evt):
dc = wx.BufferedDC(wx.ClientDC(self))
self.Draw(dc)
def OnPaint(self, evt):
dc = wx.BufferedPaintDC(self)
self.Draw(dc)
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="wx.Timer")
ClockWindow(self)
app = wx.PySimpleApp()
frm = MyFrame()
frm.Show()
app.MainLoop()
import wx
import threading
import random
class WorkerThread(threading.Thread):
"""
This just simulates some long-running task that periodically sends
a message to the GUI thread.
"""
def __init__(self, threadNum, window):
threading.Thread.__init__(self)
self.threadNum = threadNum
self.window = window
self.timeToQuit =<