目录
介绍一个VSCode轻量级 Rest API 客户端插件:Thunder Client
一、关于shebang
- 明确指定解释器
- 在shell中寻找第一个python解释器
二、Python类的私有方法/属性
Python不支持私有方法/属性,但可以将类成员方法/属性名定义为形如“__xxx”,如要访问可通过“_class__xxx”来访问,相当于做了一个“障眼法”,以避免你无意的破坏。这种做法相当于定义了私有成员。
三、PyQt图形界面的使用
1. PyQt和PySide的区别
2. 在VSCode中搭建PyQt6的开发环境
- 安装软件包
测试安装结果
-
安装插件 “PYQT Integration”
-
配置 “Pyuic” 和 “Qt Designer” 的路径
- Pyuic的路径通常位于Python环境下的Scripts\pyuic6.exe
- Qt Designer的路径通常位于Python环境下的Lib\site-packages\qt6_applications\Qt\bin\designer.exe。或者单独安装Qt6,这样Qt Designer安装结果如下:
- 打开Qt Designer界面
在VSCode资源管理器中右键点击项目目录,选择 “PYQT: New Form”,这将打开Qt Designer界面。
在设计好GUI界面后(比如新建Widget),可以生成.ui文件(实际是个XML文件),并通过编译将其转换为.py文件。编译方法如下:
或者在VSCode的界面中完成:
选择PYQT: Compile Form
随后用主程序调用生成的.py类文件即可。
可以将生成的python打包为EXE文件,然后使用Inno Setup( https://jrsoftware.org)制作安装包——如果配置脚本中有中文,需要改成GBK编码。
测试用主程序如下:
也可以:
还可以
3. 加载QSS样式文件
QSS类似CSS,用于描述控件的样式。
- QSS样式文件
- 使用代码加载QSS
- 利用QSS批量设置控件样式
QSS样式文件
使用代码设置样式(这里利用到了控件的自定义属性)
4. 在VSCode中为python程序的执行设置命令行参数
首先安装插件:Code Runner
在项目根目录的.vscode/中,配置settings.json
然后run code(Ctrl + Alt + N)。这里 “arg1 arg2 arg3” 就是命令行参数。
“$fileName”表示当前目录下的文件名。也可以使用绝对路径文件名“$fullFileName”。
5. 解决Windows控制台默认编码GBK导致的输出乱码问题
- 代码级解决方法
在向终端输出前使用如下代码
- 命令级解决方法
在执行的命令前加入环境变量的设置
- 系统级解决方法
为Windows操作系统配置环境变量
记得重启VSCode,使配置生效。
6. 信号与槽函数
信号就是事件,槽函数就是事件处理函数。可以形象地将信号看成玻璃珠,这些不同颜色的玻璃珠子倒出来会被不同的凹槽接住——实施处理。
Qt designer可以编辑信号与槽,如下:
看下ui通过pyuic自动生成的代码:
完整代码案例:
代码中的“:”和“->”分别用于注释变量类型和返回值类型。只是用于注释,没有实际的语法作用。
四、PyQt6程序的打包发布
使用Pyinstaller
1. 打包普通python程序
普通Python程序指的是完全使用Python内置模块或者对象实现的程序,程序中不包括任何第三方模块。
下面是一些常用的命令行选项:
在dist目录可以找到打包生成的exe可执行文件。
2. 打包PyQt6程序
关键是要引入PyQt6的依赖包。
需要将依赖的ui,图片等资源文件与打包生成的exe文件放入相同的文件夹,比如dist/。