使用pyinstaller打包Python3.5+PyQt5.6项目生成exe文件

来源:互联网 发布:黑社会2 知乎 编辑:程序博客网 时间:2024/05/27 19:27

  本文主要介绍如何通过pyinstaller对PyQt5项目进行打包,生成可执行的exe文件。主要针对Python3.5+PyQt5.6的环境。
  

1、Python3.5+PyQt5.6安装

  首先需要安装PyQt5.6+Python3.5编译环境,可以参考我们上一篇文章Python3.5+PyQt5.6环境搭建。安装完成后,可以运行PyQt项目。

2、pywin32安装

  pywin32是安装pyinstaller的必备项。但Python5的pip无法找到匹配的pywin32版本,pyinstaller安装时也无法自动安装pywin32。因而我们要自行下载python3.5版本可用的pywin32程序进行安装。
  可以从如下地址下载Python3.5可用的pywin32:下载地址。

注意:上述版本为python3.5 64位的,如果python3.5等为32位或v3.6,可以下载32位版本。其他各版本的下载地址为(下载地址)

3、pyinstaller安装

  完成上述步骤后,可以安装pyinstaller。有两种途径完成安装。
  一是通过pip进行安装。

pip install pyinstaller

  二是从pyinstaller官网下载安装包安装pyinstaller-3.2。下载地址

4、pyinstaller使用方法

  使用方法非常简单。因为该版本的pyinstaller已经在Python\scripts目录下生成可执行的pyinstaller.exe文件,所以可以直接在cmd命令行,进入需要打包的代码所在文件夹后,运行下面命令

pyinstaller [opts] yourprogram.py

  可选的opts有:
  -F, –onefile 打包成一个exe文件。
  -D, –onedir 创建一个目录,包含exe文件,但会依赖很多文件(默认选项)。
  -c, –console, –nowindowed 使用控制台,无界面(默认)
  -w, –windowed, –noconsole 使用窗口,无控制台

5、打包测试

采用一个calculator的代码对pyinstaller进行测试。

import sysfrom math import *from PyQt5.QtCore import *from PyQt5.QtWidgets import (QApplication, QDialog, QLineEdit, QTextBrowser,        QVBoxLayout)class Form(QDialog):    def __init__(self, parent=None):        super(Form, self).__init__(parent)        self.browser = QTextBrowser()        self.lineedit = QLineEdit("Type an expression and press Enter")        self.lineedit.selectAll()        layout = QVBoxLayout()        layout.addWidget(self.browser)        layout.addWidget(self.lineedit)        self.setLayout(layout)        self.lineedit.setFocus()        self.lineedit.returnPressed.connect(self.updateUi)        self.setWindowTitle("Calculate")    def updateUi(self):        try:            text = self.lineedit.text()            self.browser.append("%s = <b>%s</b>" % (text, eval(text)))        except:            self.browser.append("<font color=red>%s is invalid!</font>" % text)        self.lineedit.setText('')if __name__=="__main__":    app = QApplication(sys.argv)    form = Form()    form.show()    app.exec_()

代码保存为calculator.py,直接用python解释器运行,可以得到如下窗口:
calculator运行界面

打开命令行窗口,进入calculator.py所在目录。运行下面指令

pyinstaller -F -w calculator.py

pyinstaller自动执行一系列过程
生成过程

最后在同目录下的dist文件夹中生成了calculator.exe。
calculator.exe

calculator.exe运行效果与之前直接用解释器运行相同
calculator.exe运行

说明:calculator.exe可以在其他未装python的windows系统上运行。但由于采用64位python及pyinstaller,所以只能在64位系统运行

2 0
原创粉丝点击