安装PySide2
输入pip install PySide2
安装Qt for Python,如果安装过慢需要翻墙,则可以使用国内清华镜像下载,输入命令pip install --user -i https://pypi.tuna.tsinghua.edu.cn/simple PySide2
,如下图,
示例Demo
python
import random
import sys
from PySide2 import QtCore, QtWidgets, QtGui
class MyWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.hello = ["您已点击1次", "您已点击2次", "您已点击3次", "您已点击4次"]
self.button = QtWidgets.QPushButton("请点击按钮")
self.text = QtWidgets.QLabel("测试用户界面")
self.text.setAlignment(QtCore.Qt.AlignCenter)
self.layout = QtWidgets.QVBoxLayout()
self.layout.addWidget(self.text)
self.layout.addWidget(self.button)
self.setLayout(self.layout)
self.button.clicked.connect(self.magic)
def magic(self):
self.text.setText(random.choice(self.hello))
if __name__ == "__main__":
app = QtWidgets.QApplication([])
widget = MyWidget()
widget.resize(600, 400)
widget.show()
sys.exit(app.exec_())
可能报错如下,
json
Class QMacAutoReleasePoolTracker is implemented in both xxx and xxx. One of the two will be used. Which one is undefined.
该原因是mac版本下安装的opencv包包含一些qt的头文件与PyQt5冲突了,导致无法正确导入相应的包。
输入命令pip uninstall xxx
卸载掉冲突的包即可。最后输出UI界面。