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>:指定可执行文件的图标

开发 Python 桌面应用程序的一般步骤如下: 1. 确定需求: 确定应用程序的功能和特性,明确用户需求。 2. 选择 GUI 框架: 选择适合你的应用程序的图形用户界面(GUI)框架。常见的选择包括 Tkinter、PyQt、wxPython 等。 3. 设计应用程序界面: 使用所选 GUI 框架创建应用程序的用户界面。这涉及到界面布局、组件选择和排列等方面的设计。 4. 编写代码: 使用所选 GUI 框架编写应用程序的逻辑代码。这包括处理用户输入、执行功能逻辑、与其他模块的交互等。 5. 测试和调试: 对应用程序进行测试,确保其功能正常,并修复可能出现的问题。 6. 打包和发布: 将应用程序打包为可执行文件或安装程序,并发布给用户。这可以使用打包工具如 PyInstaller、cx_Freeze 等来完成。 下面是一个简单的示例,演示了使用 Tkinter 创建一个简单的桌面应用程序的步骤: ```python import tkinter as tk # 创建主窗口 window = tk.Tk() # 设计应用程序界面 label = tk.Label(window, text="Hello, World!") label.pack() # 运行主循环 window.mainloop() ``` 在上述示例中,我们首先导入了 `tkinter` 模块,并创建了一个主窗口 `window`。然后,使用 `tk.Label` 创建一个标签组件,并将其添加到主窗口中。最后,通过调用 `window.mainloop()` 来运行应用程序的主循环,使应用程序保持运行状态。 这只是一个简单的例子,具体开发过程会根据应用程序的需求和复杂度而有所不同。你可以根据自己的需求和喜好选择合适的 GUI 框架,并根据需要添加更多的组件、逻辑和功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值