在 Mac 上打包 PyQT 程序

有许多人使用 Python 来写图形化界面时选择了 PyQT,但是有许多人不知道如何将开发好的程序打包成为安装包,这篇文章我就来介绍一种非常简单的也是非常基础的在 MAC 下打包 PyQT 程序的方法。

安装 PyQT

安装 QT

我们首先要安装 QT,我这里安装的是, QT 5.5,对于 MAC 上 QT 的安装直接到官方网站上去找到对应的安装包下载安装即可。

http://www.qt.io/

安装 SIP

对于 SIP,我们也需要到官方网站去下载对应的 MAC 的源码包,安装过程如下:

1
2
3
python configure.py
sudo make
sudo make install

如果该过程中出现了 Operation not permitted 的报错信息,解决方案详见:解决 Mac OS X 10.11 安装 sip 没有权限的问题

安装 PyQT

我们需要到官方网站上去下载 PyQT5 的源码包,编译安装:

1
2
3
python configure.py
sudo make
sudo make install

需要注意的是,在 make 的过程中可能需要我们在参数中加入 QT5 的 bin 目录和 SIP 的安装目录。

安装 PyInstaller

在终端中执行:

1
sudo pip install pyinstaller

这样就安装完成了打包所需要的工具

写一个 PyQT 程序

下面我们来写一个简单的 PyQT 程序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
mport sys
from PyQt5.QtWidgets import QApplication, QWidget


if __name__ == '__main__':

app = QApplication(sys.argv)

w = QWidget()
w.resize(250, 150)
w.move(300, 300)
w.setWindowTitle('Simple')
w.show()

sys.exit(app.exec_())

执行之后:

1
python testqt.py

我们会看到一个 QT 程序:

window

将 PyQT 程序 打包

下面我们就将上面写的程序进行打包,成为 .app 文件

我们需要先对程序的入口文件运行一次打包程序(对于我的Demo就是 testqt.py):

1
pyinstaller --windowed --onefile --clean --noconfirm testqt.py

我们查看下目录有什么变化:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$ tree
.
├── build
│   └── testqt
│   ├── out00-Analysis.toc
│   ├── out00-BUNDLE.toc
│   ├── out00-EXE.toc
│   ├── out00-PKG.pkg
│   ├── out00-PKG.toc
│   ├── out00-PYZ.pyz
│   ├── out00-PYZ.toc
│   └── warntestqt.txt
├── dist
│   ├── testqt
│   └── testqt.app
│   └── Contents
│   ├── Frameworks
│   ├── Info.plist
│   ├── MacOS
│   │   └── testqt
│   └── Resources
│   └── icon-windowed.icns
├── testqt.py
└── testqt.spec

8 directories, 14 files

打开自动生成的 testqt.spec,这就是一个配置文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# -*- mode: python -*-

block_cipher = None


a = Analysis(['testqt.py'],
pathex=['/Users/jason/Project/Python/PyQt'],
binaries=None,
datas=None,
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
name='testqt',
debug=False,
strip=False,
upx=True,
console=False )
app = BUNDLE(exe,
name='testqt.app',
icon=None,
bundle_identifier=None)

我们可以修改它来打包更复杂的程序,具体参考 PyInstaller 官方文档

下面就剩下最后一步我们就能将其打包成为 .app 文件了:

1
pyinstaller --clean --noconfirm --windowed --onefile testqt.spec

我们可以看到在 dist 目录下多了一个 testqt.app,这就是我们打包完成的程序包,双击,可以正常运行。


本文的版权归作者 罗远航 所有,采用 Attribution-NonCommercial 3.0 License。任何人可以进行转载、分享,但不可在未经允许的情况下用于商业用途;转载请注明出处。感谢配合!