這篇文章主要介紹了Python之PyQT多線程串口程式碼分析,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟著小編過來看看吧
這篇部落格主要記錄PyQT多執行緒串口的主要程式碼分析,文末會有工程的原始碼檔案
首先,從PyCharm啟動QtDesigner
之前給客戶做的上位機,保密起見,刪減了大部分的框圖構件,但不影響本篇串列教學
QtDesigner介面如下:
#忽略新增資料以及表格資料顯示,這裡用不到
著重講一下類別的構成
新建一個串口類別SerialThread,繼承自QtCore.QThread,實作全部的串口收發功能
class SerialThread(QtCore.QThread): dataReadoutSignal = pyqtSignal(str) def __init__(self, parent = None, portName = 'COM3', baudrate = 9600, parity = 'N', bytesize = 8, stopbits = 1, timeout = None): super(SerialThread, self).__init__(parent) self.m_serialPort = serial.Serial() self.m_serialPort.port = portName self.m_serialPort.baudrate = baudrate self.m_serialPort.parity = parity self.m_serialPort.bytesize = bytesize self.m_serialPort.stopbits = stopbits self.m_serialPort.timeout = timeout self.OpenScom() def OpenScom(self): try: self.m_serialPort.open() self.m_serialPort.setRTS(True) self.m_serialPort.setDTR(True) except Exception as ex: print(ex) return ex def ScomSendOneData(self,datain): if isinstance(datain,int): listTemp = [] listTemp.append(datain) d = bytes(listTemp) self.m_serialPort.write(d) else: if isinstance(datain,str): d = datain.encode('utf-8') self.m_serialPort.write(d) def ScomGetintData(self): n = self.m_serialPort.inWaiting() if n: data = self.m_serialPort.read(n).hex() #writefile print(data) def ScomGetstrData(self): if self.m_serialPort.is_open: n = self.m_serialPort.inWaiting() if n > 0: data = self.m_serialPort.read(n).decode('GB2312',errors='ignore') return data def run(self): cnt = 50 while cnt <= 3000: sendstr = str(cnt) if len(sendstr) == 2: sendstr = '00' + sendstr else: if len(sendstr) == 3: sendstr = '0' + sendstr self.ScomSendOneData('SET' + sendstr + 'V') cnt = cnt + 5 print('此时设置电压为:' + sendstr + 'V') time.sleep(2)
函數功能見名知意,此處不表。這裡主要講一下run函數,run函數實作了一次循環,50到3000步進取5,發送內容是SET0050V到SET3000V,當然,我這樣做是業務需求,如果並不需要這個功能,run函數可以寫成
def run(self): while true: time.sleep(2)
介面我們用QtDesigner製作的ui檔案透過pyUIC產生py檔
產生的程式碼如下(太長,只留前幾行)
# -*- coding: utf-8 -*-# Form implementation generated from reading ui file 'CashUpdateUI11v.ui'## Created by: PyQt5 UI code generator 5.6## WARNING! All changes made in this file will be lost!from PyQt5 import QtCore, QtGui, QtWidgetsclass Ui_cash(object): def setupUi(self, cash): ** ** **
此時,新建一個類別MyWindow,繼承QMainWindow和Ui_cash,並在類別內部,建立SerialThread成員
整體程式碼如下:
class MyWindow(QMainWindow,Ui_cash): def __init__(self): super(MyWindow,self).__init__() self.scomList = [] self.threadList = [] self.setupUi(self) self.actionOpen.triggered.connect(self.openMsg) self.actionSave.triggered.connect(self.saveMsg) self.pushButton.clicked.connect(self.ScomAutoFind) self.addDataButton.clicked.connect(self.getRHandT) self.tableWidget.setColumnCount(5) self.tableWidget.setRowCount(1) self.tableWidget.setHorizontalHeaderLabels(['11', '22', '33', '44', '55']) self.tableRowCnt = 0 self.tableColumnCnt = 0 self.ThreadComID = 0 self.addDatasignal = pyqtSignal(str) self.datadict = {'RHldy':0,'Tldy':0,'meaRT':0,'voltport':0} def getMCUdata(self): if self.ThreadComID == 0: self.showMsgbox('请先连接串口') else: self.ThreadComID.ScomSendOneData(' 5501AA') time.sleep(0.1) strt = self.ThreadComID.ScomGetstrData() if strt is None: self.showMsgbox('请将串口线连接到电路板') return None print(strt) self.datadict['voltport'] = strt[4:-3] + '.' + strt[-3:-2] self.ThreadComID.ScomSendOneData(' 5502AA') time.sleep(0.1) strt = self.ThreadComID.ScomGetstrData() if strt is None: self.showMsgbox('请将串口线连接到电路板') return None print(strt) self.datadict['meaRT'] = strt[4:-4] + '.' + strt[-4:-2] return 1 def insertTableNewLine(self): self.tableWidget.setItem(self.tableRowCnt, 0, QTableWidgetItem(self.datadict['RHldy'])) self.tableWidget.setItem(self.tableRowCnt, 1, QTableWidgetItem(self.datadict['Tldy'])) self.tableWidget.setItem(self.tableRowCnt, 2, QTableWidgetItem(self.datadict['meaRT'])) self.tableWidget.setItem(self.tableRowCnt, 3, QTableWidgetItem(self.datadict['voltport'])) self.tableWidget.setItem(self.tableRowCnt, 4, QTableWidgetItem(str(datetime.date.today())+' '+str(datetime.datetime.today().hour)+':'+str(datetime.datetime.today().minute))) self.tableRowCnt += 1 self.tableWidget.insertRow(self.tableRowCnt) def openMsg(self): file,ok = QFileDialog.getOpenFileName(self,"打开记录表","C:/",".txt") def getRHandT(self): if self.ThreadComID == 0: self.showMsgbox('请先连接串口') else: data,ok = QInputDialog.getText(self, "露点仪数据", "按如下格式记录:\n RH空格T\n示例:\n RH(0~100):66.6\n T(0~200):9.8\n 输入:66.6 9.8", QLineEdit.Normal, "66.6 9.8" ) if ok == True: data = re.findall('^[0-9]+\.[0-9]+\s+[0-9]+\.[0-9]+$', data.rstrip()) if len(data) == 0: self.showMsgbox('数据格式有误,重新录入') else: data = data[0].split() print(data) self.datadict['RHldy'] = data[0] self.datadict['Tldy'] = data[1] if self.getMCUdata() is None: return None print(self.datadict) self.insertTableNewLine() else: self.showMsgbox('请重新录入数据') def showMsgbox(self,strtoshow): QMessageBox.warning(self,'提示',strtoshow,QMessageBox.Ok) def saveMsg(self): file,ok = QFileDialog.getSaveFileName(self,"保存记录表","C:/",".txt") def ScomAutoFind(self): self.pushButton.setDisabled(True) self.scomList = list(serial.tools.list_ports.comports()) if len(self.scomList) <= 0: self.showMsgbox('未发现串口,请检查线缆连接') self.pushButton.setDisabled(False) else: comNum = len(self.scomList) print(str(comNum) + 'Scom is found') while comNum: comNum = comNum - 1 if "USB" in str(self.scomList[comNum]): self.ThreadComID = SerialThread(portName=self.scomList[comNum][0]) self.ThreadComID.start() self.graphicsView.setStyleSheet("background-color: rgb(0, 255, 0);") print(str(self.scomList[comNum]) + ' is added')
由於我用的是RS232轉USB接入電腦,設備名稱是USB-SERIAL CH340,當然還有其他RS232轉USB晶片,如PL2303等。我這裡就單獨檢查USB是否在設備名稱中,沒有檢查全名,這裡要根據實際需求變動
最後就是main了,沒什麼特別
if __name__ == "__main__": app = QApplication(sys.argv) myshow = MyWindow() myshow.show() print('程序终止') sys.exit(app.exec_())
看一下實際運行效果:
實際運行,(忽略新增資料與資料記錄表….)
點選 connect後,
當然點選新增資料也是沒問題的哈
奉上全部工程文件,連結如下:
https://download.csdn.net/download/ysgjiangsu/10324162
以上是Python之PyQT多執行緒串列程式碼分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

你可以通過使用pyenv、venv和Anaconda來管理不同的Python版本。 1)使用pyenv管理多個Python版本:安裝pyenv,設置全局和本地版本。 2)使用venv創建虛擬環境以隔離項目依賴。 3)使用Anaconda管理數據科學項目中的Python版本。 4)保留系統Python用於系統級任務。通過這些工具和策略,你可以有效地管理不同版本的Python,確保項目順利運行。

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基於基於duetoc的iMplation,2)2)他們的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函數函數函數函數構成和穩定性構成和穩定性的操作,製造

數組的同質性對性能的影響是雙重的:1)同質性允許編譯器優化內存訪問,提高性能;2)但限制了類型多樣性,可能導致效率低下。總之,選擇合適的數據結構至關重要。

到CraftCraftExecutablePythcripts,lollow TheSebestPractices:1)Addashebangline(#!/usr/usr/bin/envpython3)tomakethescriptexecutable.2)setpermissionswithchmodwithchmod xyour_script.3)

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,內存效率段

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

WebStorm Mac版
好用的JavaScript開發工具

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能