设为首页 收藏本站
查看: 713|回复: 0

[经验分享] how to develop winform using python

[复制链接]

尚未签到

发表于 2017-5-2 09:37:22 | 显示全部楼层 |阅读模式
  方法一: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封装的很面向对象,使用起来也很顺手哈。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-371931-1-1.html 上篇帖子: python decorator的应用和书写 下篇帖子: python常用文件、path函数分类整理
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表