wxpython学习笔记(推荐查看)
一、简介
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。
通过这两个方法,我们就可以遍历所有选中的项了:
代码如下:
GetNextSelecteditemid = 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 = threading.Event()
self.timeToQuit.clear()
self.messageCount = random.randint(10,20)
self.messageDelay = 0.1 + 2.0 * random.random()
def stop(self):
self.timeToQuit.set()
def run(self):
msg = "Thread %d iterating %d times with a delay of %1.4f\n" \
% (self.threadNum, self.messageCount, self.messageDelay)
wx.CallAfter(self.window.LogMessage, msg)
for i in range(1, self.messageCount+1):
self.timeToQuit.wait(self.messageDelay)
if self.timeToQuit.isSet():
break
msg = "Message %d from thread %d\n" % (i, self.threadNum)
wx.CallAfter(self.window.LogMessage, msg)
else:
wx.CallAfter(self.window.ThreadFinished, self)
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Multi-threaded GUI")
self.threads = []
self.count = 0
panel = wx.Panel(self)
startBtn = wx.Button(panel, -1, "Start a thread")
stopBtn = wx.Button(panel, -1, "Stop all threads")
self.tc = wx.StaticText(panel, -1, "Worker Threads: 00")
self.log = wx.TextCtrl(panel, -1, "",
style=wx.TE_RICH|wx.TE_MULTILINE)
inner = wx.BoxSizer(wx.HORIZONTAL)
inner.Add(startBtn, 0, wx.RIGHT, 15)
inner.Add(stopBtn, 0, wx.RIGHT, 15)
inner.Add(self.tc, 0, wx.ALIGN_CENTER_VERTICAL)
main = wx.BoxSizer(wx.VERTICAL)
main.Add(inner, 0, wx.ALL, 5)
main.Add(self.log, 1, wx.EXPAND|wx.ALL, 5)
panel.SetSizer(main)
self.Bind(wx.EVT_BUTTON, self.OnStartButton, startBtn)
self.Bind(wx.EVT_BUTTON, self.OnStopButton, stopBtn)
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
self.UpdateCount()
def OnStartButton(self, evt):
self.count += 1
thread = WorkerThread(self.count, self)
self.threads.append(thread)
self.UpdateCount()
thread.start()
def OnStopButton(self, evt):
self.StopThreads()
self.UpdateCount()
def OnCloseWindow(self, evt):
self.StopThreads()
self.Destroy()
def StopThreads(self):
while self.threads:
thread = self.threads[0]
thread.stop()
self.threads.remove(thread)
def UpdateCount(self):
self.tc.SetLabel("Worker Threads: %d" % len(self.threads))
def LogMessage(self, msg):
self.log.AppendText(msg)
def ThreadFinished(self, thread):
self.threads.remove(thread)
self.UpdateCount()
app = wx.PySimpleApp()
frm = MyFrame()
frm.Show()
app.MainLoop()
4. 需要在程序中启动另外一个GUI程序,而有不失去主窗口的焦点?
通常,我们调用os.popen运行其他外部程序是没有问题的。但是在wxpython中,将会让wx失去当前的焦点,即使得打开的程序成为了一个模式对话框。要解决这个问题可以使用wx自带的方法,wx.Execute。
代码如下:
wx.Execute('notepad')
五、学习资源
1. 官方:http://wiki.wxpython.org/FrontPage
2. 啄木鸟WIKI:http://wiki.woodpecker.org.cn/moin/WxPythonInAction
作者:CoderZh(CoderZh)
出处:http://coderzh.cnblogs.com

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



A brief introduction to python GUI programming GUI (Graphical User Interface, graphical user interface) is a way that allows users to interact with computers graphically. GUI programming refers to the use of programming languages to create graphical user interfaces. Python is a popular programming language that provides a rich GUI library, making Python GUI programming very simple. Introduction to Python GUI library There are many GUI libraries in Python, the most commonly used of which are: Tkinter: Tkinter is the GUI library that comes with the Python standard library. It is simple and easy to use, but has limited functions. PyQt: PyQt is a cross-platform GUI library with powerful functions.

Introduction to pythonGUI programming PythonGUI programming, that is, graphical user interface programming, is the process of creating application program interfaces using the Python language. GUI applications usually have elements such as windows, buttons, text boxes, menus, etc., through which users can interact with the program. Python GUI programming has many benefits. First, it can make your program more beautiful and easier to use. Secondly, it can make your program cross-platform, that is, it can run on different operating systems. Third, it can make your program more flexible and easier to extend. Commonly used Python GUI libraries In Python, there are many commonly used GUI libraries, including Tkinter, PyQt, wxPython and PyG

PHP study notes: Overview of data structures and algorithms: Data structures and algorithms are two very important concepts in computer science. They are the key to solving problems and optimizing code performance. In PHP programming, we often need to use various data structures to store and operate data, and we also need to use algorithms to implement various functions. This article will introduce some commonly used data structures and algorithms, and provide corresponding PHP code examples. 1. Linear structure array (Array) Array is one of the most commonly used data structures and can be used to store ordered data.

Python is a concise, easy to learn, and efficient programming language. It is widely used in various fields such as data science, artificial intelligence, game development, network programming, etc. Although Python comes with some GUI libraries, their functions are relatively simple and cannot meet the needs of various complex applications. Therefore, there are many GUI libraries to choose from in Python, among which wxPython is one of them, which this article will introduce in detail. Introduction to wxPython wxPython is an open source, cross-platform GUI library based on

PythonGUI programming, as the name suggests, is a programming technology that uses the Python language to create a graphical user interface (GUI). Python GUI programming has many advantages, such as: cross-platform, rich third-party library support, concise syntax, etc. Therefore, Python GUI programming is deeply loved by programmers and is widely used in various types of application development. In Python GUI programming, the most commonly used third-party libraries are Tkinter, PyQt and wxPython. Tkinter is part of the Python standard library and is simple and easy to use, but has limited functionality. PyQt and wxPython are both powerful third-party GUI libraries, but they are also more

1. Basics of pythonGUI programming PythonGUI programming refers to the process of creating a graphical user interface (GUI) using the Python language. GUI is the interface for users to interact with applications, usually consisting of windows, buttons, text boxes, list boxes and other controls. Python provides a variety of GUI libraries, such as Tkinter, PyQt, wxPython, etc. These libraries provide rich controls and event handling mechanisms, allowing Python programmers to easily create beautiful and practical GUI applications. 2. Getting Started with PythonGUI Programming Installing the PythonGUI Library Before starting GUI programming, you need to install the PythonGUI library first. Taking Tkinter as an example, you can

Python is an easy-to-learn, powerful programming language suitable for development in various fields. In Python, there are a variety of graphical user interface (GUI) libraries available that help developers create interactive desktop applications. This article will introduce some commonly used Python GUI libraries and provide specific code examples. Tkinter: Tkinter is Python's standard GUI library that provides functionality for creating simple window applications. Using Tkinter, we can easily

PHP study notes: Forum and blog system development In the field of Web development, forums and blog systems are very common applications. They provide a platform for users to communicate and share information. In this article, we will discuss how to use PHP to develop a simple forum and blog system, and attach specific code examples. Environment setup First, we need to set up a development environment suitable for PHP development. We can use AMP (Apache, MySQL and PHP) packages like XAMPP or WAM
