您的位置:首页 > 编程语言 > Python开发

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

2016-08-07 02:34 851 查看
  本文主要介绍如何通过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 sys
from 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.py所在目录。运行下面指令

pyinstaller -F -w calculator.py


pyinstaller自动执行一系列过程



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



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



说明:calculator.exe可以在其他未装python的windows系统上运行。但由于采用64位python及pyinstaller,所以只能在64位系统运行
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  pyqt exe