欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

wxpython学习笔记(推荐查看)

程序员文章站 2023-11-23 18:28:04
一、简介 wxpython是python编程语言的一个gui工具箱。他使得python程序员能够轻松的创建具有健壮、功能强大的图形用户界面的程序。它是python语言对...

一、简介

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