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封装的很面向对象,使用起来也很顺手哈。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WinForm是Windows Form的简称,是基于.NET Framework平台的客户端(PC软件)开发技术,一般使用C#编程。在VS2019中,C# WinForm编程需要创建「Windows窗体应用程序」项目。Windows窗体应用程序是C#语言中的一个重要应用,也是C#语言最常见的应用。使用C#语言编写的Windows应用程序与Windows操作系统的界面类似,每个界面都是由窗体构成的,并且能通过鼠标单击、键盘输入等操作完成相应的功能。WinForm支持可视化设计,简单易上手,并可以接入大量的第三方UI库或自定义控件,给桌面应用开发带来了无限可能。\[3\] 在Python中,可以使用subprocess库(内置库,用于打开应用程序)和uiautomation库(使用pip install uiautomation安装)来实现与WinForm的交互。subprocess库可以用于执行外部命令,包括打开WinForm应用程序。uiautomation库则可以用于定位和操作WinForm应用程序中的控件,实现自动化测试或自动化操作。另外,还可以使用inspect工具和UISpy工具来辅助定位WinForm应用程序中的控件。\[2\] 所以,如果你想在Python中使用WinForm,你可以使用subprocess库来打开WinForm应用程序,并使用uiautomation库来定位和操作WinForm应用程序中的控件。同时,你还可以借助inspect工具和UISpy工具来辅助定位控件。希望这些信息对你有帮助! #### 引用[.reference_title] - *1* [python使用winform定时器](https://blog.csdn.net/u014584014/article/details/127421407)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [适用于winform程序的UI自动化实现(python+uiautomation)](https://blog.csdn.net/qq_32828053/article/details/122232861)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Winform](https://blog.csdn.net/xxxcAxx/article/details/128245473)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值