python桌面程序开发 wxpython、pyinstaller

基于wxpython的GUI开发

wxpython库的安装

wxpython在windows系统和正常的库安装类似

pip install wxpython

第一个例子

最简单的弹出一个标题为“Hello World”的窗口

# First things, first. Import the wxPython package.
import wx
# Next, create an application object.
app = wx.App()
# Then a frame.
frm = wx.Frame(None, title="Hello World")
# Show it.
frm.Show()
# Start the event loop.
app.MainLoop()

结果如下图所示
hello world!

第二个例子

实现一些较为复杂的功能

#!/usr/bin/env python
"""
Hello World, but with more meat.
"""

import wx

class HelloFrame(wx.Frame):
    """
    A Frame that says Hello World
    """

    def __init__(self, *args, **kw):
        # ensure the parent's __init__ is called
        super(HelloFrame, self).__init__(*args, **kw)

        # create a panel in the frame
        pnl = wx.Panel(self)

        # put some text with a larger bold font on it
        st = wx.StaticText(pnl, label="Hello World!")
        font = st.GetFont()
        font.PointSize += 10
        font = font.Bold()
        st.SetFont(font)

        # and create a sizer to manage the layout of child widgets
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(st, wx.SizerFlags().Border(wx.TOP|wx.LEFT, 25))
        pnl.SetSizer(sizer)

        # create a menu bar
        self.makeMenuBar()

        # and a status bar
        self.CreateStatusBar()
        self.SetStatusText("Welcome to wxPython!")


    def makeMenuBar(self):
        """
        A menu bar is composed of menus, which are composed of menu items.
        This method builds a set of menus and binds handlers to be called
        when the menu item is selected.
        """

        # Make a file menu with Hello and Exit items
        fileMenu = wx.Menu()
        # The "\t..." syntax defines an accelerator key that also triggers
        # the same event
        helloItem = fileMenu.Append(-1, "&Hello...\tCtrl-H",
                "Help string shown in status bar for this menu item")
        fileMenu.AppendSeparator()
        # When using a stock ID we don't need to specify the menu item's
        # label
        exitItem = fileMenu.Append(wx.ID_EXIT)

        # Now a help menu for the about item
        helpMenu = wx.Menu()
        aboutItem = helpMenu.Append(wx.ID_ABOUT)

        # Make the menu bar and add the two menus to it. The '&' defines
        # that the next letter is the "mnemonic" for the menu item. On the
        # platforms that support it those letters are underlined and can be
        # triggered from the keyboard.
        menuBar = wx.MenuBar()
        menuBar.Append(fileMenu, "&File")
        menuBar.Append(helpMenu, "&Help")

        # Give the menu bar to the frame
        self.SetMenuBar(menuBar)

        # Finally, associate a handler function with the EVT_MENU event for
        # each of the menu items. That means that when that menu item is
        # activated then the associated handler function will be called.
        self.Bind(wx.EVT_MENU, self.OnHello, helloItem)
        self.Bind(wx.EVT_MENU, self.OnExit,  exitItem)
        self.Bind(wx.EVT_MENU, self.OnAbout, aboutItem)


    def OnExit(self, event):
        """Close the frame, terminating the application."""
        self.Close(True)


    def OnHello(self, event):
        """Say hello to the user."""
        wx.MessageBox("Hello again from wxPython")


    def OnAbout(self, event):
        """Display an About Dialog"""
        wx.MessageBox("This is a wxPython Hello World sample",
                      "About Hello World 2",
                      wx.OK|wx.ICON_INFORMATION)


if __name__ == '__main__':
    # When this module is run (not imported) then create the app, the
    # frame, show it, and start the event loop.
    app = wx.App()
    frm = HelloFrame(None, title='Hello World 2')
    frm.Show()
    app.MainLoop()

结果为下图所示
在这里插入图片描述

深入研究

使用wxFormBuilder软件进行页面设计,并获取python代码,软件的下载地址为https://sourceforge.net/projects/wxformbuilder/
然后再进行业务逻辑开发
在wxFormBuilder进行页面设计,得到的代码如下,并命名为frame.py

# -*- coding: utf-8 -*-

###########################################################################
## Python code generated with wxFormBuilder (version Jun 17 2015)
## http://www.wxformbuilder.org/
##
## PLEASE DO "NOT" EDIT THIS FILE!
###########################################################################

import wx
import wx.xrc


###########################################################################
## Class Frame
###########################################################################

class Frame(wx.Frame):

    def __init__(self, parent):
        wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=u"Hello World", pos=wx.DefaultPosition,
                          size=wx.Size(500, 300), style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL)

        self.SetSizeHintsSz(wx.DefaultSize, wx.DefaultSize)

        bSizer1 = wx.BoxSizer(wx.VERTICAL)

        self.caption = wx.StaticText(self, wx.ID_ANY, u"简单的加法计算", wx.DefaultPosition, wx.DefaultSize, 0)
        self.caption.Wrap(-1)
        bSizer1.Add(self.caption, 0, wx.ALL, 5)

        self.text1 = wx.TextCtrl(self, wx.ID_ANY, u"0", wx.DefaultPosition, wx.DefaultSize, 0)
        bSizer1.Add(self.text1, 0, wx.ALL, 5)

        self.cal = wx.StaticText(self, wx.ID_ANY, u"+", wx.DefaultPosition, wx.DefaultSize, 0)
        self.cal.Wrap(-1)
        bSizer1.Add(self.cal, 0, wx.ALL, 5)

        self.text2 = wx.TextCtrl(self, wx.ID_ANY, u"0", wx.DefaultPosition, wx.DefaultSize, 0)
        bSizer1.Add(self.text2, 0, wx.ALL, 5)

        self.button_main = wx.Button(self, wx.ID_ANY, u"计算", wx.DefaultPosition, wx.DefaultSize, 0)
        bSizer1.Add(self.button_main, 0, wx.ALL, 5)

        self.result = wx.TextCtrl(self, wx.ID_ANY, u"0", wx.DefaultPosition, wx.DefaultSize, 0)
        bSizer1.Add(self.result, 0, wx.ALL, 5)

        self.SetSizer(bSizer1)
        self.Layout()

        self.Centre(wx.BOTH)

        # Connect Events
        self.button_main.Bind(wx.EVT_BUTTON, self.main_button_click)

    def __del__(self):
        pass

    # Virtual event handlers, overide them in your derived class
    def main_button_click(self, event):
        event.Skip()

再写一个main.py即可实现加法功能

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wx
import frame


class Window(frame.Frame):
    def init_main_window(self):
        self.text1.SetValue('0')
        self.text2.SetValue('0')

    def main_button_click(self, event):
        try:
            res = int(self.text1.GetValue()) + int(self.text2.GetValue())
            self.result.SetValue(str(res))
        except:
            self.result.SetValue('输入有误,请重输')


if __name__ == '__main__':
    app = wx.App()
    main_win = Window(None)
    main_win.init_main_window()
    main_win.Show()
    app.MainLoop()

基于pyinstaller打包为exe程序

第一步安装pywin32模块

pip install pywin32

第二步安装pyinstaller模块

pip install pyinstaller

第三步使用pyinstaller进行打包,如

pyinstaller -F demo.py

打包命令一般用 pyinstaller -F <源文件名.py>
其他参数包括:
–clean:清除打包过程中生成的临时目录:pychache、build
-D,–onedir:生成包含可执行文件的文件夹,而不是单个可执行文件
-F,–onefile:生成单个可执行文件(方便)
-i <图标文件.iclo>:指定可执行文件的图标

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值