程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

python桌面程序開發 wxpython、pyinstaller

編輯:Python

python桌面程序開發 wxpython、pyinstaller

  • 基於wxpython的GUI開發
    • wxpython庫的安裝
    • 第一個例子
    • 第二個例子
    • 深入研究
  • 基於pyinstaller打包為exe程序

基於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()

結果如下圖所示

第二個例子

實現一些較為復雜的功能

#!/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>:指定可執行文件的圖標


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved