py2exe打包pyqt程序

前几天看到铂金小鸟写的 osc for PC 客户端,python和css、js、html几种语言写的windows程序,我非常感兴趣。于是自己摸索了一下windows平台下不用C++和C#写带UI的程序。

用到的软件

py2exe
py2exe is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation.
说白了,py2exe就是让那些没有安装python的用户也能执行python写的程序。它的作用就是打包python成二进制文件。至于ubuntu等系统如何打包,我就不知道了。我安装的版本是:py2exe-0.6.9.win32-py2.7.zip pyqt
PyQt is a set of Python v2 and v3 bindings for Digia's Qt application framework and runs on all platforms supported by Qt including Windows, MacOS/X and Linux. PyQt5 supports Qt v5. PyQt4 supports Qt v4 and will build against Qt v5. The bindings are implemented as a set of Python modules and contain over 620 classes.
简而言之,pyqt就是一个工具,让python也能调用qt的强大的UI库文件。

命令行界面

安装好两个工具后,先写一个hello world。 在你的工作目录下,新建一个文件名为 hello.py,内容是:
print "Hello World!"
然后在当前目录下新建一个文件名为setup.py,内容是:
from distutils.core import setup
import py2exe

setup(console=['hello.py'])#注意此处的console关键字,如果是带有UI界面的软件,那么为windows
然后在命令行中执行以下语句,配置编译环境
python setup.py install
最后执行以下语句,打包程序
python setup.py py2exe
此处如果遇到错误:
File "form1.pyc", line 11, in ?
  File "qt.pyc", line 9, in ?
  File "qt.pyc", line 7, in __load
ImportError: No module named sip
参考 http://www.py2exe.org/index.cgi/Py2exeAndPyQt,我们可以知道修改命令为:
python setup.py py2exe --includes sip
即可。当然文中也提到了其他方法。 你会发现当前目录下多了build和dist文件夹,cd到dist文件夹,然后hello.exe即可看到令人激动的"Hello World!"了。切忌不要直接点击hello.exe执行,以为会一闪而过,啥也没有。而且即使程序错了,你也不知道,我也帮不了你了。。。

漂亮的UI界面

在你的程序目录下,新建一个文件,名为windows.py:
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
app = QtGui.QApplication(sys.argv)

widget = QtGui.QWidget()
widget.resize(250, 150)
widget.setWindowTitle('windows UI')
widget.show()

sys.exit(app.exec_())
至于为什么这样写,详细解析见: http://jimmykuu.sinaapp.com/static/PyQt4_Tutorial/html/first_programs.html 把setup.py改为
import py2exe
import sys

from distutils.core import setup

setup(windows=['windows.py'])#看清楚了此处是windows,如果为console,你会看到难看的命令行界面在UI的后面。。。
然后分别执行
python setup.py py2exe
python setup.py py2exe --includes sip

 

参考:

转载于:https://my.oschina.net/itfanr/blog/195694

猜你喜欢

转载自blog.csdn.net/weixin_34245169/article/details/91799626