笔记Pythonpyqt图形化
小楼夜听雨在安装pyqt之前,我们先创建虚拟环境,由于我们使用qt开发完软件之后,需要打包成exe程序,所以通过创建虚拟环境之后再安装模块和包,那么后面打包的时候就只会打包虚拟环境里面的模块和库,避免exe程序过于臃肿
创建虚拟环境
在PyCharm中,在左下角的解释器中选择添加,选择新生成,地址选择目前的项目路径
基本ui
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import sys from PyQt5.QtWidgets import QApplication,QWidget if __name__ == "__main__": app = QApplication(sys.argv) w=QWidget() w.setWindowTible("第一个pyqt") w.show() app.exec_()
|
控件
按钮
1 2 3 4 5 6 7 8 9 10
| from PyQt5.QtWidgets import QPushButton
bth = QPushButton("按钮")
bth.setParent(w)
bth = QPushButton("按钮",w)
|
文本
1 2 3 4 5 6 7
| from PyQt5.QtWidgets import QLabel
label = QLabel("账号:",w)
label.setGeometry(20,20,30,30)
|
输入框
1 2 3 4 5 6 7
| from PyQt5.QtWidgets import QLineEdit
LineEdit = QLineEdit(w) LineEdit.setPlaceholderText("请输入") LineEdit.setGeometry(20,20,30,30)
|
窗口
窗口大小
窗口位置
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| w.move(0,0)
|
设置窗口图标
1 2
| from PyQt5.QtGui import QIcon w.setWindowIcon(QIcon('favicon.ico'))
|
信号和槽
语法 对象.信号.connect.(槽函数)
通过窗口控件的对象的信号绑定槽函数,当对象的信号被触发的时候,槽函数被调用
自定义信号
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| from PyQt5.QtCore import pyqtSignal
class MYwindow (QWidget): MYxh = pyqtSignal(str) def init_ui(self): self.ui= uic.loadUi("./untitled.ui") bth =self.ui.pushButton bth.clicked.connect(self.B) self.MYxh.connect(self.A) def A(self,a): print(a) def B (self): self.MYxh.emit("aaa")
|
QT designer
下载
1
| pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyqt5-tools
|
终端启动
加载
设计好ui之后,保存之后
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
| import sys from PyQt5.QtWidgets import QApplication, QWidget from PyQt5 import uic
class MYwindow (QWidget): def __init__(self): super().__init__() self.init_ui()
def init_ui(self): self.ui= uic.loadUi("./untitled.ui") print(self.ui.__dict__) print(self.ui.label) print(self.ui.label.text) print(self.ui.label.text())
if __name__ == "__main__": app = QApplication(sys.argv)
w = MYwindow()
w.ui.show()
app.exec_()
|
打包
下载pyinstaller
1
| pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyinstaller
|
终端导航到项目目录,打开主脚本
1
| pyinstaller -F main.py -w
|