• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

wxpython学习笔记(推荐查看)

python 搞代码 4年前 (2022-01-09) 13次浏览 已收录 0个评论

一、简介

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<BR>import sys, glob, random<BR>import data</P><P>class DemoFrame(wx.Frame):<BR>    def __init__(self):<BR>        wx.Frame.__init__(self, None, -1,<BR>                          "wx.ListCtrl in wx.LC_REPORT mode",<BR>                          size=(600,400))</P><P>        il = wx.ImageList(16,16, True)<BR>        for name in glob.glob("smicon??.png"):<BR>            bmp = wx.Bitmap(name, wx.BITMAP_TYPE_PNG)<BR>            il_max = il.Add(bmp)<BR>        self.list = wx.ListCtrl(self, -1, style=wx.LC_REPORT)<BR>        self.list.AssignImageList(il, wx.IMAGE_LIST_SMALL)</P><P>        # Add some columns<BR>        for col, text in enumerate(data.columns):<BR>            self.list.InsertColumn(col, text)</P><P>        # add the rows<BR>        for item in data.rows:<BR>            index = self.list.InsertStringItem(sys.maxint, item[0])<BR>            for col, text in enumerate(item[1:]):<BR>                self.list.SetStringItem(index, col+1, text)</P><P>            # give each item a random image<BR>            img = random.randint(0, il_max)<BR>            self.list.SetItemImage(index, img, img)<br><br>        # set the width of the columns in various ways<BR>        self.list.SetColumnWidth(0, 120)<BR>        self.list.SetColumnWidth(1, wx.LIST_AUTOSIZE)<BR>        self.list.SetColumnWidth(2, wx.LIST_AUTOSIZE)<BR>        self.list.SetColumnWidth(3, wx.LIST_AUTOSIZE_USEHEADER)</P><P><BR>app = wx.PySimpleApp()<BR>frame = DemoFrame()<BR>frame.Show()<BR>app.MainLoop()<BR>

对于ListCtrl控件,我要补充的几个地方是:

1. 如何获取选中的项目?

最常用的方法就是获取选中的第一项:GetFirstSelected(),这个函数返回一个int,即ListCtrl中的项(Item)的ID。

还有一个方法是:GetNextSelected(itemid),获取指定的itemid之后的第一个被选中的项,同样也是返回itemid。

通过这两个方法,我们就可以遍历所有选中的项了:

GetNextSelecteditemid = self.list.GetFirstSelected()<BR>while itemid  -1:<BR>        #Do something<BR>        itemid = self.list.GetNextSelected(itemid)<BR>

如果要获取某一行,某一列的值,则通过下面的方法:

#获取第0行,第1列的值<BR>itemtext = self.list.GetItem(0, 1).Text<BR>

2. 如何在选定项后添加右键菜单?

在__init__函数中,添加如下的事件绑定:
self.list.Bind(wx.EVT_CONTEXT_MENU, self.OnContextMenu)然后,添加OnContextMenu方法:

def OnContextMenu(self, event):<BR>        if not hasattr(self, "popupStop"):<BR>            self.popupStop = wx.NewId()<BR>            self.popupPropery = wx.NewId()<BR>            self.Bind(wx.EVT_MENU, self.OnPopupStop, id = self.popupStop)<BR>            self.Bind(wx.EVT_MENU, self.OnPopupProperty, id = self.popupPropery)<br><br>        # 创建菜单<BR>        menu = wx.Menu()<BR>        itemStop = wx.MenuItem(menu, self.popupStop, "Stop")<BR>        itemProperty = wx.MenuItem(menu, self.popupPropery, 'Property')<br><br>        menu.AppendItem(itemStop)<BR>        menu.AppendItem(itemProperty)<br><br>        itemProperty.Enable(False)#默认让属性按钮变成无效状态<br><br>        if itemid == -1:#如果没有选中任何项<BR>            itemStop.Enable(False)<BR>        else:<BR>            itemStop.Enable(False)<BR>            itemProperty.Enable(True)<BR>        #到这里才弹出菜单<BR>        self.PopupMenu(menu)<BR>        #最后注意销毁前面创建的菜单<BR>        menu.Destroy()<BR>

5. 选择文件对话框(FileDialog)

使用起来非常简单:

dlg = wx.FileDialog(self, <BR>                            message="Yes, select a place ",<BR>                            wildcard="PNG(*.png)|*.png" ,<BR>                            style=wx.SAVE<BR>                            )<BR>        savefile = ''<BR>        if dlg.ShowModal() == wx.ID_OK:<BR>            savefile = dlg.GetPath()<BR>            try:<BR>                os.remove(self.filename)<BR>            except:<BR>                pass<BR>            self.img.SaveFile(savefile, wx.BITMAP_TYPE_PNG)<BR>            self.filename = savefile<BR>        dlg.Destroy()<BR>

6. 选择文件夹对话框(DirDialog)

dialog = wx.DirDialog(None, 'Choose a directory: ',<BR>                              style = wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)<BR>if dialog.ShowModal() == wx.ID_OK:<BR>        for itemid in range(self.list.GetItemCount()):<BR>                self.savechart(itemid, graphpath)<BR>dialog.Destroy()<BR>

四、一些技巧

1. 设置快捷键

比如,希望按F5执行某个操作,可以在__init__函数中使用如下方法:

acceltbl = wx.AcceleratorTable([(wx.ACCEL_NORMAL, wx.WXK_F5, self.btnrun.GetId())])<BR>self.SetAcceleratorTable(acceltbl)<BR>

还有一种很常用的情况,就是按ESC键关闭窗口。我们知道,有一种非常简单的办法就是使用SetId(wx.ID_CANCEL)方法,如:

self.btncancel = wx.Button(self.panel1, -1, 'Cancel', wx.Point(380, 280))<BR>self.btncancel.SetId(wx.ID_CANCEL)<BR>

这样,按ESC键时,将会关闭当前Dialog,注意!这里是说Dialog,即继承自wx.Dialog的窗口对象,对于wx.Frame使用SetId似乎没有效果。

2. 使用定时器timer
在《wxPythonInAction》18章有个例子,如下:

import wx<BR>import time</P><P>class ClockWindow(wx.Window):<BR>    def __init__(self, parent):<BR>        wx.Window.__init__(self, parent)<BR>        self.Bind(wx.EVT_PAINT, self.OnPaint)<BR>        self.timer = wx.Timer(self)<BR>    <a style="color:transparent">本文来源gao($daima.com搞@代@#码(网5</a>    self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)<BR>        self.timer.Start(1000)</P><P>    def Draw(self, dc):<BR>        t = time.localtime(time.time())<BR>        st = time.strftime("%I:%M:%S", t)<BR>        w, h = self.GetClientSize()<BR>        dc.SetBackground(wx.Brush(self.GetBackgroundColour()))<BR>        dc.Clear()<BR>        dc.SetFont(wx.Font(30, wx.SWISS, wx.NORMAL, wx.NORMAL))<BR>        tw, th = dc.GetTextExtent(st)<BR>        dc.DrawText(st, (w-tw)/2, (h)/2 - th/2)<br><br>    def OnTimer(self, evt):<BR>        dc = wx.BufferedDC(wx.ClientDC(self))<BR>        self.Draw(dc)</P><P>    def OnPaint(self, evt):<BR>        dc = wx.BufferedPaintDC(self)<BR>        self.Draw(dc)</P><P>class MyFrame(wx.Frame):<BR>    def __init__(self):<BR>        wx.Frame.__init__(self, None, title="wx.Timer")<BR>        ClockWindow(self)<BR>        </P><P>app = wx.PySimpleApp()<BR>frm = MyFrame()<BR>frm.Show()<BR>app.MainLoop()<BR>

3. 使用多线程时你必须知道的:wx.CallAfter

在wxpython中编写多线程案例时特别需要注意,线程中通知窗口对象更新状态时,必须使用wx.CallAfter。同样是18章的例子:

import wx<BR>import threading<BR>import random</P><P>class WorkerThread(threading.Thread):<BR>    """<BR>    This just simulates some long-running task that periodically sends<BR>    a message to the GUI thread.<BR>    """<BR>    def __init__(self, threadNum, window):<BR>        threading.Thread.__init__(self)<BR>        self.threadNum = threadNum<BR>        self.window = window<BR>        self.timeToQuit = threading.Event()<BR>        self.timeToQuit.clear()<BR>        self.messageCount = random.randint(10,20)<BR>        self.messageDelay = 0.1 + 2.0 * random.random()</P><P>    def stop(self):<BR>        self.timeToQuit.set()</P><P>    def run(self):<BR>        msg = "Thread %d iterating %d times with a delay of %1.4f\n" \<BR>              % (self.threadNum, self.messageCount, self.messageDelay)<BR>        wx.CallAfter(self.window.LogMessage, msg)</P><P>        for i in range(1, self.messageCount+1):<BR>            self.timeToQuit.wait(self.messageDelay)<BR>            if self.timeToQuit.isSet():<BR>                break<BR>            msg = "Message %d from thread %d\n" % (i, self.threadNum)<BR>            wx.CallAfter(self.window.LogMessage, msg)<BR>        else:<BR>            wx.CallAfter(self.window.ThreadFinished, self)<br><br>            </P><P>class MyFrame(wx.Frame):<BR>    def __init__(self):<BR>        wx.Frame.__init__(self, None, title="Multi-threaded GUI")<BR>        self.threads = []<BR>        self.count = 0<br><br>        panel = wx.Panel(self)<BR>        startBtn = wx.Button(panel, -1, "Start a thread")<BR>        stopBtn  = wx.Button(panel, -1, "Stop all threads")<BR>        self.tc = wx.StaticText(panel, -1, "Worker Threads: 00")<BR>        self.log = wx.TextCtrl(panel, -1, "",<BR>                               style=wx.TE_RICH|wx.TE_MULTILINE)</P><P>        inner = wx.BoxSizer(wx.HORIZONTAL)<BR>        inner.Add(startBtn, 0, wx.RIGHT, 15)<BR>        inner.Add(stopBtn, 0, wx.RIGHT, 15)<BR>        inner.Add(self.tc, 0, wx.ALIGN_CENTER_VERTICAL)<BR>        main = wx.BoxSizer(wx.VERTICAL)<BR>        main.Add(inner, 0, wx.ALL, 5)<BR>        main.Add(self.log, 1, wx.EXPAND|wx.ALL, 5)<BR>        panel.SetSizer(main)</P><P>        self.Bind(wx.EVT_BUTTON, self.OnStartButton, startBtn)<BR>        self.Bind(wx.EVT_BUTTON, self.OnStopButton, stopBtn)<BR>        self.Bind(wx.EVT_CLOSE,  self.OnCloseWindow)</P><P>        self.UpdateCount()</P><P>    def OnStartButton(self, evt):<BR>        self.count += 1<BR>        thread = WorkerThread(self.count, self)<BR>        self.threads.append(thread)<BR>        self.UpdateCount()<BR>        thread.start()<br><br>    def OnStopButton(self, evt):<BR>        self.StopThreads()<BR>        self.UpdateCount()<br><br>    def OnCloseWindow(self, evt):<BR>        self.StopThreads()<BR>        self.Destroy()</P><P>    def StopThreads(self):<BR>        while self.threads:<BR>            thread = self.threads[0]<BR>            thread.stop()<BR>            self.threads.remove(thread)<br><br>    def UpdateCount(self):<BR>        self.tc.SetLabel("Worker Threads: %d" % len(self.threads))<br><br>    def LogMessage(self, msg):<BR>        self.log.AppendText(msg)<br><br>    def ThreadFinished(self, thread):<BR>        self.threads.remove(thread)<BR>        self.UpdateCount()<BR>        </P><P>app = wx.PySimpleApp()<BR>frm = MyFrame()<BR>frm.Show()<BR>app.MainLoop()<BR>

4. 需要在程序中启动另外一个GUI程序,而有不失去主窗口的焦点?
通常,我们调用os.popen运行其他外部程序是没有问题的。但是在wxpython中,将会让wx失去当前的焦点,即使得打开的程序成为了一个模式对话框。要解决这个问题可以使用wx自带的方法,wx.Execute。

wx.Execute('notepad')<BR>

五、学习资源

1. 官方:http://wiki.wxpython.org/FrontPage

2. 啄木鸟WIKI:http://wiki.woodpecker.org.cn/moin/WxPythonInAction

作者:CoderZh(CoderZh)
出处:http://coderzh.cnblogs.com


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:wxpython学习笔记(推荐查看)

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址