[python] 初识 PyQt5
昨天想着用 Python 写个展示的 demo,之前打算熟悉一下 PyQt ,正好边学边做,学以致用。
主要的流程是在 cmd 下运行 .exe 并读取输出结果,运到的困难是如何实时回传数据以及修改图片大小并显示(缩放到固定大小)。
以下是代码,只展示框架,部分参数未设置。基于 Python3 + PyQt5
import os import time
import sys
import subprocess from configparser import ConfigParser from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * class Example(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.command = "" self.inipath = r"" self.cf = ConfigParser() self.cf.read(self.inipath) main_ground = QWidget() self.setCentralWidget(main_ground) grid = QGridLayout() grid.setSpacing(10) self.title = QLabel('Result',self) self.titleEdit = QLineEdit(self) self.label = QLabel("photo",self) self.title.setGeometry(30,30,50,25) self.title.setFont(QFont('SansSerif', 12)) """ grid.addWidget(self.title,1,0) grid.addWidget(self.titleEdit,1,1) grid.addWidget(self.label,2,0,5,5) main_ground.setLayout(grid) """ self.statusBar() QAction() QAction.triggered.connect() menubar = self.menuBar() RunMenu = menubar.addMenu('&Run') RunMenu.addAction() EditMenu = menubar.addMenu('&Edit') EditMenu.addAction() self.setGeometry(300, 300, 740, 480) self.setWindowTitle('VehicleDetect') #self.setWindowFlags(Qt.WindowMinimizeButtonHint) #禁止调整窗口大小 self.setFixedSize(self.width(), self.height()) self.show() def Action(self): self.cf.set() self.cf.write(open(self.inipath,'w')) self.showDialog() if self.fname[0]: self.command = '' subprocess.call(self.command) print("\n",end = "") return def showDialog(self): self.fname = QFileDialog.getOpenFileName(self, 'Open file', r'D:\') return def update_item_data(self,data): self.titleEdit.setText(data) ResultPath = r'' imglist = os.listdir(ResultPath) if int(data): imgshow = os.path.join(ResultPath,imglist[-1]) image = QImage() image.load(imgshow) #self.label.setPixmap(QPixmap(imgshow)) self.label.setPixmap(QPixmap.fromImage(image).scaled(self.label.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)); class UpdateData(QThread): data = pyqtSignal(str) cnt = 0 def run(self): while(True): cnt = len(os.listdir(r'')) self.data.emit(str(cnt)) time.sleep(1) if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() update_thread = UpdateData() update_thread.data.connect(ex.update_item_data) update_thread.start() sys.exit(app.exec_())