how to develop winform using python

方法一:PyQT


Qt是一个跨平台的界面库,PyQt就是它的Python版本了,Python的界面库除了PyQt之外,还有wxPython,TK等。
环境:Windows+Python2.6+Qt
1.下载安装环境
python2.6:www.python.org
PyQt2.6:http://www.riverbankcomputing.co.uk/static/Downloads/PyQt4/PyQt-Py2.6-gpl-4.7-1.exe
eric4:http://nchc.dl.sourceforge.net/project/eric-ide/eric4/stable/4.4.0/eric4-4.4.0.zip
eric4是PyQt界面编译器,也可以当作Python的IDE

安装好eric4之后,在Python26\Lib\site-packages\eric4\目录下有个eric4.pyw文件,双击,就打开了eric4编辑器,
初次打开,会有一个配置窗口(Settings-->Preferences),简单配置一下:

Editor-->APIs-->勾上Complie APIs Autocompation,Language中选择Pyhton,点击Add from installed APIs,选择eric4.api或其它你需要的APIs。然后点击下面的”Compile APIs”,这里会需要点时间。结束后点Apply,配置结束。

2.demo

2.1 Project-->New,新建一个工程,起名Hello吧;
2.2 点击编辑器左边Project-Viewer中第二个选项卡Forms,空白处,右键鼠标-->New Form, 弹出对话框选择Dialog,命名Hello,保存之后,自动弹出Qt4的设计窗口(双击UI文件也可以弹出)
2.3 设计窗口左边拉两个按钮,btnClick,btnExit,拉个Edit框
2.4 事件
点击窗口右面的(信号/槽编辑器)中的加号(+),就会出现一条没有定义过的事件,此时在发送者选择btnExit,信号中选择clicked(),接受者中选择Dialog,槽中选择close(),然后保存后关闭设计器。
2.5 在eric界面,在From选项卡中会出现名为Hello.ui文件,在文件名右键,选择Compile Form,选择Generate Dialog Code,设定ClassName,点击右面的New按钮,默认就可以。确定之后,在下面的文本框中,选择btnClick下的第一个on_btnClick_clicked()打上勾,然后OK,回到Project-Viewer下的第一个选项卡Source,双击Hello.py,修改如下

修改

def on_btnClick_clicked(self):   
    """  
    Slot documentation goes here.  
    """  
    # TODO: not implemented yet   
    #raise NotImplementedError   
    self.editTxt.setText("Hello, PyQt!")  
    def on_btnClick_clicked(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        #raise NotImplementedError
        self.editTxt.setText("Hello, PyQt!") 
 



新增:

if __name__ == '__main__':   
        app = QApplication(sys.argv)   
           
        dlog = Dialog()   
        dlog.show()   
           
        sys.exit(app.exec_())  
if __name__ == '__main__':
        app = QApplication(sys.argv)
        
        dlog = Dialog()
        dlog.show()
        
        sys.exit(app.exec_()) 

 按F5运行

 

方法二:

wxPython是一个基于wxWidgets的跨平台界面库

环境是Windows XP+Python2.6+wxPython2.8。wxPython下载地址:http://downloads.sourceforge.net/project/wxpython/wxPython/2.8.9.2/wxPython2.8-win32-unicode-2.8.9.2-py26.exe?use_mirror=nchc。

1. 第一个demo(使用提供的PySimpleAPP),对于demo,先来code再解释:

#coding=utf8   
#!usr/bin/env python   
  
import wx   
class MyFrame(wx.Frame):   
    def __init__(self):   
        print 'MyFrame.__init__'  
        wx.Frame.__init__(self, None, -1, "demo1", size=(300,400))   
        panel = wx.Panel(self, -1)   
        panel.Bind(wx.EVT_MOTION, self.OnMove)   
        wx.StaticText(panel, -1, "Pos:", pos=(10,12))   
        self.posCtrl = wx.TextCtrl(panel, -1, "", pos=(40,10))   
           
    def OnMove(self, event):   
        pos = event.GetPosition()   
        self.posCtrl.SetValue("%s, %s" % (pos.x, pos.y))   
           
           
if __name__ == '__main__':   
#    app = wx.PySimpleApp(True)   
    app = wx.PySimpleApp(True, "demo1.log")   
    frame = MyFrame()   
    frame.Show(True)   
    app.MainLoop()  
#coding=utf8
#!usr/bin/env python

import wx
class MyFrame(wx.Frame):
    def __init__(self):
        print 'MyFrame.__init__'
        wx.Frame.__init__(self, None, -1, "demo1", size=(300,400))
        panel = wx.Panel(self, -1)
        panel.Bind(wx.EVT_MOTION, self.OnMove)
        wx.StaticText(panel, -1, "Pos:", pos=(10,12))
        self.posCtrl = wx.TextCtrl(panel, -1, "", pos=(40,10))
        
    def OnMove(self, event):
        pos = event.GetPosition()
        self.posCtrl.SetValue("%s, %s" % (pos.x, pos.y))
        
        
if __name__ == '__main__':
#    app = wx.PySimpleApp(True)
    app = wx.PySimpleApp(True, "demo1.log")
    frame = MyFrame()
    frame.Show(True)
    app.MainLoop()  

 对于一个应用来说,必不可少的是需要一个wx.APP,一个Frame,所以每个应用必须至少包含这两个,上面的实例也一样,接下来一句一句解释,先从‘__main__’看起:

    app = wx.PySimpleApp(True, "demo1.log")  #起一个App,第一个参数表示是否输出打印,第二个参数表示输出的文件名,若第二个参数为None,则输出到窗口中。
    frame = MyFrame() #起一个Frame
    frame.Show(True)  #显示
    app.MainLoop()      # 交出执行权,进入消息循环

在自定义的MyFrame类中,首先调用基类的初始化函数__init__;然后给Frame增加一个控件Panel,接着给panel绑定wx.EVT_MOTION事件,并设定了回调函数self.OnMove;继续增加控件StaticText;继续增加控件TextCtrl;在回调函数OnMove中,设置postion;

 

import os   
import time   
import datetime   
import wx   
  
class PyOnDemandOutputWindow:   
    """  
    A class that can be used for redirecting Python's stdout and  
    stderr streams.  It will do nothing until something is wrriten to  
    the stream at which point it will create a Frame with a text area  
    and write the text there.  
    """  
    def __init__(self, title = "wxPython: stdout/stderr"):   
        self.frame  = None  
        self.title  = title   
        self.pos    = wx.DefaultPosition   
        self.size   = (450, 300)   
        self.parent = None  
        self.triggers = []   
        self.logfile = None  
  
    def SetParent(self, parent):   
        """Set the window to be used as the popup Frame's parent."""  
        self.parent = parent   
  
  
    def RaiseWhenSeen(self, trigger):   
        """  
        Trigger is a string or list of strings that will cause the  
        output window to be raised when that trigger text is written.  
        """  
        import types   
        if type(trigger) in types.StringTypes:   
            trigger = [trigger]   
        self.triggers = trigger   
           
  
    def CreateOutputWindow(self, st):   
        self.frame = wx.Frame(self.parent, -1, self.title, self.pos, self.size,   
                              style=wx.DEFAULT_FRAME_STYLE)   
        self.text  = wx.TextCtrl(self.frame, -1, "",   
                                 style=wx.TE_MULTILINE|wx.TE_READONLY)   
        self.text.AppendText(st)   
        self.frame.Show(True)   
        self.frame.Bind(wx.EVT_CLOSE, self.OnCloseWindow)   
           
  
    def CreateOutputFile(self, st):   
        self.logfile = file("log.txt", "ab")   
        self.write(st)   
  
    def OnCloseWindow(self, event):   
        if self.frame is not None:   
            self.frame.Destroy()   
        self.frame = None  
        self.text  = None  
        self.parent = None  
  
  
    # These methods provide the file-like output behaviour.   
    def write(self, text):   
        """  
        Create the output window if needed and write the string to it.  
        If not called in the context of the gui thread then uses  
        CallAfter to do the work there.  
        """           
        if self.logfile is None:   
            if not wx.Thread_IsMain():   
                wx.CallAfter(self.CreateOutputFile, text)   
            else:   
                self.CreateOutputFile(text)   
        else:   
            if not wx.Thread_IsMain():   
                wx.CallAfter(self.__write, text)   
            else:   
                self.__write(text)   
  
    def __write(self, text):   
        # helper function for actually writing the text, and   
        # optionally raising the frame if needed   
        dt_now = datetime.datetime.now()   
        dt_now_str = dt_now.strftime("%Y-%m-%d %H:%M:%S")   
           
        self.logfile.write('[%s] %s%s' % (dt_now_str, text, os.linesep))   
  
  
    def close(self):   
        if self.frame is not None:   
            wx.CallAfter(self.frame.Close)   
           
        if self.logfile is not None:   
            self.logfile.flush()   
            self.logfile.close()   
  
  
    def flush(self):   
        if self.logfile is not None:   
            self.logfile.flush()   
     
wxPython封装的很面向对象,使用起来也很顺手哈。

你可能感兴趣的:(how to develop winform using python)