Python Qt GUI设计:做一款串口调试助手(实战篇—1)
目錄
1、UI設計
2、將UI文件轉換為Py文件
3、邏輯功能實現
3.1、初始化程序
3.2、串口檢測程序
3.3、?設置及打開串口程序
3.4、定時發送數據程序
3.5、發送數據程序
3.6、接收數據程序
3.7、保存日志程序
3.8、加載日志程序
3.9、打開博客、公眾號程序
3.10、清除發送和接收數據顯示程序
3.11、關閉串口程序
Python Qt GUI設計系列博文終于到了實戰篇,本篇博文將貫穿之前的基礎知識點實現一款串口調試助手。
關注【公眾號】 美男子玩編程,回復關鍵字:串口調試助手,獲取項目源碼~
資源下載:PythonQt串口調試助手-嵌入式文檔類資源-CSDN下載
1、UI設計
UI設計使用Qt Creator實現,組件布局如下所示:
2、將UI文件轉換為Py文件
這里使用Python腳本的方式將UI文件轉換為Python文件,代碼如下所示:
import os import os.pathdir ='./' #文件所在的路徑#找出路徑下所有的.ui文件 def listUiFile():list = []files = os.listdir(dir)for filename in files:#print(filename)if os.path.splitext(filename)[1] == '.ui':list.append(filename)return list#把擴展名未.ui的轉換成.py的文件 def transPyFile(filename):return os.path.splitext(filename)[0] + '.py'#通過命令把.ui文件轉換成.py文件 def runMain():list = listUiFile()for uifile in list:pyfile = transPyFile(uifile)cmd = 'pyuic5 -o {pyfile} {uifile}'.format(pyfile=pyfile, uifile=uifile)os.system(cmd)if __name__ =="__main__":runMain()3、邏輯功能實現
3.1、初始化程序
首先初始化一些組件和標志位的狀態,設置信號與槽的關系,實現代碼如下所示:
# 初始化程序def __init__(self):super(Pyqt5_Serial, self).__init__()self.setupUi(self)self.init()self.ser = serial.Serial()self.port_check()# 設置Logo和標題self.setWindowIcon(QIcon('Com.png'))self.setWindowTitle("串口調試助手 【公眾號】美男子玩編程")# 設置禁止拉伸窗口大小self.setFixedSize(self.width(), self.height())# 發送數據和接收數據數目置零self.data_num_sended = 0self.Lineedit2.setText(str(self.data_num_sended))self.data_num_received = 0self.Lineedit3.setText(str(self.data_num_received))# 串口關閉按鈕使能關閉self.Pushbuttom3.setEnabled(False)# 發送框、文本框清除self.Text1.setText("")self.Text2.setText("")# 建立控件信號與槽關系def init(self):# 串口檢測按鈕self.Pushbuttom2.clicked.connect(self.port_check)# 串口打開按鈕self.Pushbuttom1.clicked.connect(self.port_open)# 串口關閉按鈕self.Pushbuttom3.clicked.connect(self.port_close)# 定時發送數據self.timer_send = QTimer()self.timer_send.timeout.connect(self.data_send)self.Checkbox7.stateChanged.connect(self.data_send_timer)# 發送數據按鈕self.Pushbuttom6.clicked.connect(self.data_send)# 加載日志self.Pushbuttom4.clicked.connect(self.savefiles)# 加載日志self.Pushbuttom5.clicked.connect(self.openfiles)# 跳轉鏈接self.commandLinkButton1.clicked.connect(self.link)# 清除發送按鈕self.Pushbuttom7.clicked.connect(self.send_data_clear)# 清除接收按鈕self.Pushbuttom8.clicked.connect(self.receive_data_clear)3.2、串口檢測程序
檢測電腦上所有串口,實現代碼如下所示:
# 串口檢測def port_check(self):# 檢測所有存在的串口,將信息存儲在字典中self.Com_Dict = {}port_list = list(serial.tools.list_ports.comports())self.Combobox1.clear()for port in port_list:self.Com_Dict["%s" % port[0]] = "%s" % port[1]self.Combobox1.addItem(port[0])# 無串口判斷if len(self.Com_Dict) == 0:self.Combobox1.addItem("無串口")3.3、?設置及打開串口程序
檢測到串口后進行配置,打開串口,并且啟動定時器一直接收用戶輸入,實現代碼如下所示:
# 打開串口def port_open(self):self.ser.port = self.Combobox1.currentText() # 串口號self.ser.baudrate = int(self.Combobox2.currentText()) # 波特率flag_data = int(self.Combobox3.currentText()) # 數據位if flag_data == 5:self.ser.bytesize = serial.FIVEBITSelif flag_data == 6:self.ser.bytesize = serial.SIXBITSelif flag_data == 7:self.ser.bytesize = serial.SEVENBITSelse:self.ser.bytesize = serial.EIGHTBITSflag_data = self.Combobox4.currentText() # 校驗位if flag_data == "None":self.ser.parity = serial.PARITY_NONEelif flag_data == "Odd":self.ser.parity = serial.PARITY_ODDelse:self.ser.parity = serial.PARITY_EVENflag_data = int(self.Combobox5.currentText()) # 停止位if flag_data == 1:self.ser.stopbits = serial.STOPBITS_ONEelse:self.ser.stopbits = serial.STOPBITS_TWOflag_data = self.Combobox6.currentText() # 流控if flag_data == "No Ctrl Flow":self.ser.xonxoff = False #軟件流控self.ser.dsrdtr = False #硬件流控 DTRself.ser.rtscts = False #硬件流控 RTSelif flag_data == "SW Ctrl Flow":self.ser.xonxoff = True #軟件流控else: if self.Checkbox3.isChecked():self.ser.dsrdtr = True #硬件流控 DTRif self.Checkbox4.isChecked():self.ser.rtscts = True #硬件流控 RTStry:time.sleep(0.1)self.ser.open()except:QMessageBox.critical(self, "串口異常", "此串口不能被打開!")return None# 串口打開后,切換開關串口按鈕使能狀態,防止失誤操作 if self.ser.isOpen():self.Pushbuttom1.setEnabled(False)self.Pushbuttom3.setEnabled(True)self.formGroupBox1.setTitle("串口狀態(開啟)")# 定時器接收數據self.timer = QTimer()self.timer.timeout.connect(self.data_receive)# 打開串口接收定時器,周期為1msself.timer.start(1)3.4、定時發送數據程序
通過定時器,可支持1ms至30s之間數據定時,實現代碼如下所示:
# 定時發送數據def data_send_timer(self):try:if 1<= int(self.Lineedit1.text()) <= 30000: # 定時時間1ms~30s內if self.Checkbox7.isChecked():self.timer_send.start(int(self.Lineedit1.text()))self.Lineedit1.setEnabled(False)else:self.timer_send.stop()self.Lineedit1.setEnabled(True)else:QMessageBox.critical(self, '定時發送數據異常', '定時發送數據周期僅可設置在30秒內!')except:QMessageBox.critical(self, '定時發送數據異常', '請設置正確的數值類型!')3.5、發送數據程序
可以發送ASCII字符和十六進制類型數據,并且可以在數據前顯示發送的時間,在數據后進行換行,發送一個字節,TX標志會自動累加,實現代碼如下所示:
# 發送數據def data_send(self):if self.ser.isOpen():input_s = self.Text2.toPlainText()# 判斷是否為非空字符串if input_s != "":# 時間顯示if self.Checkbox5.isChecked():self.Text1.insertPlainText((time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + " ")# HEX發送if self.Checkbox1.isChecked(): input_s = input_s.strip()send_list = []while input_s != '':try:num = int(input_s[0:2], 16)except ValueError:QMessageBox.critical(self, '串口異常', '請輸入規范十六進制數據,以空格分開!')return Noneinput_s = input_s[2:].strip()send_list.append(num)input_s = bytes(send_list)# ASCII發送else: input_s = (input_s).encode('utf-8')# HEX接收顯示if self.Checkbox2.isChecked(): out_s = ''for i in range(0, len(input_s)):out_s = out_s + '{:02X}'.format(input_s[i]) + ' 'self.Text1.insertPlainText(out_s)# ASCII接收顯示else: self.Text1.insertPlainText(input_s.decode('utf-8')) # 接收換行 if self.Checkbox6.isChecked():self.Text1.insertPlainText('\r\n')# 獲取到Text光標textCursor = self.Text1.textCursor()# 滾動到底部textCursor.movePosition(textCursor.End)# 設置光標到Text中去self.Text1.setTextCursor(textCursor)# 統計發送字符數量num = self.ser.write(input_s)self.data_num_sended += numself.Lineedit2.setText(str(self.data_num_sended))else:pass3.6、接收數據程序
可以接收ASCII字符和十六進制類型數據,并且可以在數據前顯示發送的時間,在數據后進行換行,接收一個字節,RX標志會自動累加,實現代碼如下所示:
# 接收數據def data_receive(self):try:num = self.ser.inWaiting()if num > 0:time.sleep(0.1)num = self.ser.inWaiting() #延時,再讀一次數據,確保數據完整性except:QMessageBox.critical(self, '串口異常', '串口接收數據異常,請重新連接設備!')self.port_close()return Noneif num > 0:data = self.ser.read(num)num = len(data)# 時間顯示if self.Checkbox5.isChecked():self.Text1.insertPlainText((time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + " ")# HEX顯示數據if self.Checkbox2.checkState():out_s = ''for i in range(0, len(data)):out_s = out_s + '{:02X}'.format(data[i]) + ' 'self.Text1.insertPlainText(out_s)# ASCII顯示數據else:self.Text1.insertPlainText(data.decode('utf-8'))# 接收換行 if self.Checkbox6.isChecked():self.Text1.insertPlainText('\r\n')# 獲取到text光標textCursor = self.Text1.textCursor()# 滾動到底部textCursor.movePosition(textCursor.End)# 設置光標到text中去self.Text1.setTextCursor(textCursor)# 統計接收字符的數量self.data_num_received += numself.Lineedit3.setText(str(self.data_num_received))else:pass3.7、保存日志程序
將接收框中收發的數據保存到TXT文本中,實現代碼如下所示:
# 保存日志def savefiles(self):dlg = QFileDialog()filenames = dlg.getSaveFileName(None, "保存日志文件", None, "Txt files(*.txt)")try:with open(file = filenames[0], mode='w', encoding='utf-8') as file:file.write(self.Text1.toPlainText())except:QMessageBox.critical(self, '日志異常', '保存日志文件失敗!')3.8、加載日志程序
加載保存到TXT文本中的數據信息到發送框中,實現代碼如下所示:
# 加載日志def openfiles(self):dlg = QFileDialog()filenames = dlg.getOpenFileName(None, "加載日志文件", None, "Txt files(*.txt)")try:with open(file = filenames[0], mode='r', encoding='utf-8') as file:self.Text2.setPlainText(file.read())except:QMessageBox.critical(self, '日志異常', '加載日志文件失敗!')3.9、打開博客、公眾號程序
點擊按鈕,打開我的公眾號二維碼和博客主頁,實現代碼如下所示:
# 打開博客鏈接和公眾號二維碼def link(self):dialog = QDialog()label_img = QLabel()label_img.setAlignment(Qt.AlignCenter) label_img.setPixmap(QPixmap("./img.jpg"))vbox = QVBoxLayout()vbox.addWidget(label_img)dialog.setLayout(vbox)dialog.setWindowTitle("快掃碼關注公眾號吧~")dialog.setWindowModality(Qt.ApplicationModal)dialog.exec_()webbrowser.open('https://blog.csdn.net/m0_38106923')3.10、清除發送和接收數據顯示程序
清除發送數據框和接收數據框的內容和計數次數,實現代碼如下所示:
# 清除發送數據顯示def send_data_clear(self):self.Text2.setText("")self.data_num_sended = 0self.Lineedit2.setText(str(self.data_num_sended))# 清除接收數據顯示def receive_data_clear(self):self.Text1.setText("")self.data_num_received = 0self.Lineedit3.setText(str(self.data_num_received))3.11、關閉串口程序
關閉串口,停止定時器,重置組件和標志狀態,實現代碼如下所示:
# 關閉串口def port_close(self):try:self.timer.stop()self.timer_send.stop()self.ser.close()except:QMessageBox.critical(self, '串口異常', '關閉串口失敗,請重啟程序!')return None# 切換開關串口按鈕使能狀態和定時發送使能狀態self.Pushbuttom1.setEnabled(True)self.Pushbuttom3.setEnabled(False)self.Lineedit1.setEnabled(True)# 發送數據和接收數據數目置零self.data_num_sended = 0self.Lineedit2.setText(str(self.data_num_sended))self.data_num_received = 0self.Lineedit3.setText(str(self.data_num_received))self.formGroupBox1.setTitle("串口狀態(關閉)")資源下載:PythonQt串口調試助手-嵌入式文檔類資源-CSDN下載?
總結
以上是生活随笔為你收集整理的Python Qt GUI设计:做一款串口调试助手(实战篇—1)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 毕业论文排版素材大学计算机基础,毕业论文
- 下一篇: php元素周期表,元素周期表 - 理视天