安装 PyQt5 环境
在 PyCharm 里面安装 PyQt5
pip install PyQt5 -i https://pypi.douban.com/simple
在 PyCharm 里面安装 Qt 的工具包
pip install PyQt5-tools -i https://pypi.douban.com/simple
QT 官网:https://doc.qt.io/
Cursor 指针
QT 提供了十分便捷的设置鼠标形状的方法,在 QT 界面的根类 QWidget 中有 QCursor cursor()
self.Button.setCursor(Qt.WaitCursor)
self.Button.setCursor(Qt.PointingHandCursor)
self.Button.setCursor(Qt.ArrowCursor)
PointingHandCursor 变为手型
CrossCursor 变为十字型
ArrowCursor 变为箭头型
UpArrowCursor 变为向上箭头型
IBeamCursor 变为文本输入型
WaitCursor 变为等待型
BusyCursor 变为繁忙型
ForbiddenCursor 变为禁止型
WhatsThisCursor 变为问号型
SizeVerCursor 变为垂直拖拽型
SizeHorCursor 变为水平拖拽性
SizeBDiagCursor 变为对角线调整大小型
SizeAllCursor 变为移动对象型
SplitHCursor 变为水平拆分型
SplitVCursor 变为垂直拆分型
OpenHandCursor 变为打开型
ClosedHandCursor 变为关闭型
BlankCursor 变为空白型
读取展示图片
imgName, imgType = QFileDialog.getOpenFileName(self, "打开图片", "", "*.jpg;;*.png")
jpg = QtGui.QPixmap(imgName).scaled(240, 240)
self.logoImage.setPixmap(jpg)
储存图片
fileName, tmp = QFileDialog.getSaveFileName(self, "保存数学派图标", "", "*.jpg;;*.png")
im = Image.open(self.imageResource)
im.save(fileName)
重写拖动事件
def mouseMoveEvent(self, e: QMouseEvent):
self._endPos = e.pos() - self._startPos
self.move(self.pos() + self._endPos)
def mousePressEvent(self, e: QMouseEvent):
if e.button() == Qt.LeftButton:
self._isTracking = True
self._startPos = QPoint(e.x(), e.y())
def mouseReleaseEvent(self, e: QMouseEvent):
if e.button() == Qt.LeftButton:
self._isTracking = False
self._startPos = None
self._endPos = None
常见报错
SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes
in position 2-3: truncated \UXXXXXXXX escape
pyinstaller 打包
通过生成 spec 文件的命令,针对代码的主程序文件生成打包对应的 spec 文件
pyi-makespec app.py
pyinstaller 是一个常用的Python打包工具,可以将Python代码打包成独立的可执行文件。下面是常用的 pyinstaller 打包参数,可以根据实际需要进行设置。
参数 | 作用 |
---|---|
-F 或 --onefile | 将生成的文件打包成单个可执行文件,方便发布和使用。 |
-w 或 --windowed | 将生成的可执行文件隐藏命令行窗口,使其更加美观。 |
-n 或 --name | 指定生成的可执行文件的名称。 |
-i 或 --icon | 指定生成的可执行文件的图标。 |
–hidden-import | 指定需要引入的隐藏模块。 |
–add-data | 指定需要打包的数据文件。 |
–upx | 使用UPX压缩可执行文件,减小文件大小。 |
–clean | 在打包之前清除缓存和临时文件。 |
根据 spec 生成 exe 文件
pyinstaller app.spec
在 datas 配置静态资源文件
a = Analysis(
['app.py'],
pathex=[],
binaries=[],
datas=[('icon.png', '.')],
hiddenimports=[],
hookspath=[],
hooksconfig={
},
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False,
)
打包完成后,此时 dist下 只有一个可执行文件,运行这个可执行文件,出现错误,找不到静态资源文件。
原因:运行可执行文件时,会先将可执行文件进行压缩,压缩的位置在 /tmp 下,再执行,所以被打包进去的数据文件在被解压的路径下,而程序是在运行的路径下搜索,即可执行文件的目录下,所以找不到数据文件。
解决方案:配置运行时 tmp 目录
import os
import sys
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
return os.path.join(base_path, relative_path)