python+pyqt5 串口助手

import sys
from time import sleep
import serial
from PyQt5 import QtGui, QtWidgets
from PyQt5.QtSerialPort import QSerialPortInfo
from selenium import webdriver
from wigth import Ui_widget  # 主窗口
from wigtha import Ui_Form  # 子窗口
#import serial.tools.list_ports#用来获取所有串口的信息
class Widget(QtWidgets.QWidget,Ui_Form):
    def __init__(self):
        super(Widget, self).__init__()
        self.setupUi(self) #初始化子窗口类下的setupUi 函数
    def save_message(self):
        my_pyqt_wigth.setWindowTitle(("提示\n信息:"))
        font=QtGui.QFont()
        font.setPointSize(18)
        my_pyqt_wigth.label.setFont(font)
        my_pyqt_wigth.label.setText("保存成功")
    def serial_open_error_mage(self):
        my_pyqt_wigth.setWindowTitle(("Error:"))
       #设置子窗口中lab1的字体大小及内容
        font = QtGui.QFont()
        font.setPointSize(12)
        my_pyqt_wigth.label.setFont(font)
        my_pyqt_wigth.label.setText('串口打开失败:\n未检测到串口\n或串口已占用')
class MyQT_From(QtWidgets.QWidget,Ui_widget): #主窗口
    def __init__(self):
        super(MyQT_From, self).__init__()
        self.setupUi(self)#初始化主窗口类下的setupUi 函数
        self.serial_message()
        self.number = 0
        self.pushButton_false()#控制按钮Disable
        self.pushButton_2.setShortcut('Ctrl+o')## 设置快捷键---> 打开串口,在设置快捷键时,属性值不能改变,否则无法再继续执行,若设置PUSHBUTTON11的话,
        # 就只能在运行软件时执行一次,故在打开串口的下方增加了一个按钮pushbutton2,用来使用快捷键的功能
        #self.pushButton_11.setShortcut('Alt+x')  # 设置快捷键---> 打开串口
        self.pushButton_6.setShortcut('alt+c')  # 设置快捷键--->检测串口
        self.pushButton_8.setShortcut('Up')#设置快捷键---->箭头上
        self.pushButton_9.setShortcut('Down')#设置快捷键---->箭头下
        self.pushButton_5.setShortcut('Left')#设置快捷键---->箭头左
        self.pushButton_7.setShortcut('Right')#设置快捷键---->箭头右
        self.pushButton_10.setShortcut('Return')  # 设置快捷键主键盘区域及笔记本电脑仅有的Enter
        #self.pushButton_10.setShortcut('Enter')  # 设置快捷键数字区域Enter
    def closeEvent(self, a0: QtGui.QCloseEvent) -> None:#重构主线程,否则会有循环的线程无法关闭
        sys.exit(app.exec_())
        #self.comboBox.currentIndexChanged.connect(self.pyqt5_serial)
    '''def pushbutton_click(self):        #    textBrowser 用法示例
        self.textBrowser.clear()
        a = ['sgsg','sagwipowg','976uj','mjjhu9765','kjhgy7896','sgsg','sagwipowg','976uj','mjjhu9765','kjhgy7896']
        self.sj=a
        s=self.textEdit.toPlainText()#获取textEdit文本框的内容
        self.textBrowser.append(s)
        QtWidgets.QApplication.processEvents()  # 刷新界面防止出现假死现象
        for i in a:
           # print(i)
            #self.textEdit.toPlainText()#获取文本框的内容
            self.textBrowser.append(i)
            sleep(0.1)
            #time.sleep(0.1)
            QtWidgets.QApplication.processEvents()#刷新界面防止出现假死现象
        self.serial_message()'''
    def save_as(self):#用于打开文件
        #下行代码为查找路径,第一个参数,有self的话用self,没有的话用None,
        # 第二个参数,设置窗口名。
        # 第三个参数,默认文件名称,路径为软件所在的路径
        # 第四个参数,列出可以进行筛选的参数,第一个是默认的,多个用双分号分开。
        # 打开文件
        # a=QtWidgets.QFileDialog.getOpenFileNames(None, "请选择要查找的文件", "path", "Text File(*.txt);;ALL Files(*)")
        #保存文件:
        try:
            filename = QtWidgets.QFileDialog.getSaveFileName(None, "保存文件", "Serial", "Text File(*.txt);;ALL Files(*)")
            with open(filename[0], 'w')as f:
                f.write(self.textBrowser.toPlainText())
                QtWidgets.QApplication.processEvents()
                sleep(0.05)
                f.close()
                QtWidgets.QApplication.processEvents()
            my_pyqt_wigth.show()#显示窗口
            my_pyqt_wigth.save_message()#配置窗口信息(保存成功)
        except:
            pass
           # exit()#退出主程序
    def pyqt5_serial(self):  # 用pyqt5 获取串口信息
        self.comboBox.clear()#先清空值,再获取
       # self.comboBox.clear()# 获取串口信息
        self.port_list = QSerialPortInfo.availablePorts()
        #print(len(self.port_list))
        if len(self.port_list) >= 1:
            print(len(self.port_list))
            self.comboBox.clear()#清空Combobox内容
            #print(port_list[0].portName)
            for i in self.port_list:
                self.seri_name = i.portName()#注:i.portName()
                print(self.seri_name)
                self.comboBox.addItem(self.seri_name,"1")
            QtWidgets.QApplication.processEvents()
        else:
            #my_pyqt_wigth.show()
           # self.comboBox.currentIndexChanged['QString'].connect(self.refresh_combobox())
            QtWidgets.QApplication.processEvents()
            print(len(self.port_list))
            #pass
            #self.comboBox.setItemText(0,("串口选择"))
            #self.comboBox.clear()
        #self.port_Arduino=QSerialPortInfo(self.seri_name)
       # print(self.port_Arduino.isBusy())
    def serial_message(self):
        baud_rate_group = QSerialPortInfo.standardBaudRates()#回在当前系统平台上可用的标准波特率列表
        for i in baud_rate_group:
            self.comboBox_2.addItem((str(i)), "1") #获取波特率
        self.comboBox_2.setCurrentIndex(6)  # 设置默认值
        #self.comboBox_2.currentText()#获取当前值
        #print(baud_rate_group)
        stop_group = ['2', '1.5', '1']
        data_group = ['5', '6', '7', '8']
        parity_check_group = ['N', '奇校验', '偶校验']
       # self.comboBox_2.addItems(baud_rate_group)
        self.comboBox_3.addItems(stop_group)#停止位
        self.comboBox_3.setCurrentIndex(2)#设置默认值
        self.comboBox_4.addItems(data_group)#数据位
        self.comboBox_4.setCurrentIndex(3)#设置默认值
        self.comboBox_5.addItems(parity_check_group)#奇偶校验
        self.comboBox_5.setCurrentIndex(0)#设置默认值
       # port_list = list(serial.tools.list_ports.comports())  # 获取所有串口的信息,可用len来判断是否有串口
       # for i in port_list:
        #    str_i = str(i)
         #   len_i = len(str_i)
          #  print(i)
           # for a in range(int(len_i)):
            #    if str_i[a] == '-'and a!=0:
             #       self.s_name = str_i[0:a]
              #      print(self.s_name)
               #     break
            #self.comboBox.addItem(self.s_name,0)
        QtWidgets.QApplication.processEvents()  # 刷新界面防止出现假死现象
        self.pyqt5_serial()
        #self.comboBox.addItem("")
        #self.comboBox.addItems(a)
        # self.comboBox.addItems(["uxyi","sgk;","sjglk"])#正确的添加方式
        # self.comboBox.addItems(i)#也可以用self.comboBox.insertItems(a,i)


    def serial_open_button(self):
        bt_value = self.pushButton_11.text()#打开串口按键文本设置
       # print(bt_value)
        if bt_value == '打开串口':
            serial_name1 = self.comboBox.currentText()  # 获取串口
            self.port_mes = QSerialPortInfo(serial_name1)  #
            self.serial_port_state = self.port_mes.isBusy()
            if self.serial_port_state == False:
                #如下为初始化串口:
                self.port = serial.Serial()
                self.port.port = self.comboBox.currentText()
                self.port.baudrate = self.comboBox_2.currentText()
                self.port.stopbits = int(self.comboBox_3.currentText())
                self.port.bytesize = int(self.comboBox_4.currentText())
                self.port.timeout = None     # set a timeout value, None for waiting forever
                self.port.xonxoff = 0     # enable software flow control
                self.port.rtscts = 0      # enable RTS/CTS flow control
                self.port.interCharTimeout = None   # Inter-character timeout, None to disable
                #self.port.parity="N"
                #self.port.parity=self.comboBox_5.currentText()
                #baud_rate = self.comboBox_2.currentText()
                #stop_bit = self.comboBox_3.currentText()
                #data_bit = self.comboBox_4.currentText()#要为int型数据
                #parity_check = self.comboBox_5.currentText()
                #print(serial_name1, baud_rate, stop_bit, data_bit, parity_check)

                #self.port_Arduino=QSerialPortInfo(self.seri_name)# 判断串口是否占用,若是则返回True,反之返回False
                #self.serial_port_state=self.port_Arduino.isBusy()
                #print(self.port_Arduino.isBusy())
                try:
                    #打开串口
                    #self.port = serial.Serial(serial_name1, baud_rate, int(data_bseit), parity=serial.PARITY_NONE)#打开串口
                    #self.port.open()
                    self.port.open()
                    self.port_mes = QSerialPortInfo(self.seri_name)# 判断串口状态,若是则返回True,反之返回False
                    self.serial_port_state = self.port_mes.isBusy()
                    if self.serial_port_state == True:#再增加一个判断串口是否占用,若已占用,说明已打开成功
                        self.pushButton_11.setText("关闭串口")  # 串口打开成功后状态显示为打开状态,即关闭
                        self.pushButton_ture()#成功打开串口后,再使能相关按钮
                        self.receive_data(1)#打开成功后接收使能打开
                        QtWidgets.QApplication.processEvents()
                except:
                    my_pyqt_wigth.show()
                    my_pyqt_wigth.serial_open_error_mage()
                    print("串口打开失败")
                    pass
            else:
                my_pyqt_wigth.show()
                my_pyqt_wigth.serial_open_error_mage()
                my_pyqt_wigth.label.setText("串口被占用")
                #print("串口已打开")
                #print(self.serial_port_state)
        elif bt_value == '关闭串口':
            self.pushButton_false()
            self.receive_data(0)
            sleep(0.05)
            #time.sleep(0.2)
            #print(type(self.port))
            self.port.close()
            self.pushButton_11.setText("打开串口")
            #print(type(self.port))
        else:
            pass
    def serial_open_combobox(self,port):
       # bt_value=self.pushButton_11.text()  # 打开串口按键文本设置
        # print(bt_value)
        serial_name1 = self.comboBox.currentText()  # 获取串口
        self.port_mes = QSerialPortInfo(serial_name1)  #
        self.serial_port_state = self.port_mes.isBusy()
        if self.serial_port_state == False:
            # 如下为初始化串口:
            self.port = serial.Serial(0)
            self.port.port = self.comboBox.currentText()
            self.port.baudrate = self.comboBox_2.currentText()
            self.port.stopbits = int(self.comboBox_3.currentText())
            self.port.bytesize = int(self.comboBox_4.currentText())
            self.port.close()#先关闭串口,再打开
            sleep(0.1)

            # self.port.parity="N"
            # self.port.parity=self.comboBox_5.currentText()
            # baud_rate = self.comboBox_2.currentText()
            # stop_bit = self.comboBox_3.currentText()
            # data_bit = self.comboBox_4.currentText()#要为int型数据
            # parity_check = self.comboBox_5.currentText()
            # print(serial_name1, baud_rate, stop_bit, data_bit, parity_check)

            # self.port_Arduino=QSerialPortInfo(self.seri_name)# 判断串口是否占用,若是则返回True,反之返回False
            # self.serial_port_state=self.port_Arduino.isBusy()
            # print(self.port_Arduino.isBusy())
            try:
                # 打开串口
                # self.port = serial.Serial(serial_name1, baud_rate, int(data_bit), parity=serial.PARITY_NONE)#打开串口
                # self.port.open()
                self.port.open()
                self.port_mes = QSerialPortInfo(self.seri_name)  # 判断串口状态,若是则返回True,反之返回False
                self.serial_port_state = self.port_mes.isBusy()
                if self.serial_port_state == True:  # 再增加一个判断串口是否占用,若已占用,说明已打开成功
                    self.pushButton_11.setText("关闭串口")  # 串口打开成功后状态显示为关闭状态
                    self.receive_data(1)  # 打开成功后接收使能打开
                    QtWidgets.QApplication.processEvents()
            except:
                my_pyqt_wigth.show()
                my_pyqt_wigth.serial_open_error_mage()
                print("串口打开失败")
                pass
        else:
            my_pyqt_wigth.show()
            my_pyqt_wigth.serial_open_error_mage()
            my_pyqt_wigth.label.setText("串口被占用")
            # print("串口已打开")
            # print(self.serial_port_state)


    def window_open(self):#打开子窗口
        my_pyqt_wigth.show() #显示子窗口
        my_pyqt_wigth.message()#调用子窗口参数
    def com_clear(self):
        self.comboBox.clear()
    def refresh_combobox(self):
        self.pyqt5_serial()
    def clear_data(self):
        self.textBrowser.clear()
    def serial_send(self):# 向下位机发送数据

        print(self.pushButton_11.text())
        if self.pushButton_11.text() == '关闭串口':
        #在发送前,先判断串口是否打开
            send_value = self.textEdit.toPlainText()#获取 输入文本框的内容
            sleep(0.05)
            #time.sleep(0.1)
            print(send_value)
            self.port.write('\n'.encode('gbk'))
            self.port.write(send_value.encode('gbk'))
            self.port.write('\r\n'.encode('gbk'))
            # s.write('\n1\r\n'.encode('gbk'))  #发送数据的格式,若格式错误,则无法接收数据
            sleep(0.05)
            #time.sleep(0.1)
        else:
            print("请先打开串口")
    def receive_data(self, sate):
        #self.sate=sate
        #print(sate)
        while sate:
            try:
                QtWidgets.QApplication.processEvents()# 刷新界面防止出现假死现象
                sleep(0.01)
                #time.sleep(0.1)
                m = self.port.inWaiting()  # 获取接收到的数据长度
                if m:
                    self.receive_value = self.port.read(m).decode('gbk')#接收数据并解码显示
                    sleep(0.01)
                    #print(self.receive_value)
                    a=self.receive_value
                    #print(type(a))
                    if a==None:
                        print('请重新启动硬件')
                    elif a == "8": #当值=7的时候就停止加UP
                        print("--------------")
                        print(a)
                        self.textBrowser.append(self.receive_value)#添加数据到textBrowser,后面要有延时,否则主程序是死机
                        #self.pushButton_8.clicked.connect(self.message())
                        self.pushButton_8.setEnabled(False)#当值到达上限时就便按钮使能为False
                    elif a == "9": #当值=7的时候就停止减down
                        print("--------------")
                        print(a)
                        self.textBrowser.append(self.receive_value)#添加数据到textBrowser,后面要有延时,否则主程序是死机
                        #self.pushButton_8.clicked.connect(self.message())
                        self.pushButton_9.setEnabled(False)#当值到达下限时就便按钮使能为False
                    elif a == "10": #当值=7的时候就停止加left
                        print("--------------")
                        print(a)
                        self.textBrowser.append(self.receive_value)#添加数据到textBrowser,后面要有延时,否则主程序是死机
                        #self.pushButton_8.clicked.connect(self.message())
                        self.pushButton_5.setEnabled(False)#当值到达下限时就便按钮使能为False
                    elif a == "11": #当值=7的时候就停止减right
                        print("--------------")
                        print(a)
                        self.textBrowser.append(self.receive_value)#添加数据到textBrowser,后面要有延时,否则主程序是死机
                        #self.pushButton_8.clicked.connect(self.message())
                        self.pushButton_7.setEnabled(False)#当值到达下限时就便按钮使能为False
                    else:
                        print(self.receive_value)
                        #self.textBrowser.append(self.receive_value)  # 添加数据到textBrowser,后面要有延时,否则主程序是死机
                       # self.pushButton_8.clicked.connect(self.up())
                    # print(value)
                    #print(type(value))
                    #print(self.receive_value)
                       # self.pushButton_8.clicked.connect(self.message())
                    sleep(0.05)
                    #time.sleep(0.1)
                     # self.textBrowser.setText(value)#设置显示的数据
                    #print(value)
                    QtWidgets.QApplication.processEvents()  # 刷新界面防止出现假死现象
                    self.radioButton.setChecked(True)
                    #print(type(self.port))
            except:
                break
    def up(self):#pushButton8
        try:
            self.radioButton.setChecked(False)#指示灯
            self.pushButton_9.setEnabled(True)
            self.pushButton_10.setEnabled(True)
            value1 = "1"
            sleep(0.01)
            self.port.write('\n'.encode('gbk'))
            self.port.write(value1.encode('gbk'))
            self.port.write('\r\n'.encode('gbk'))
            self.receive_data(1)
            sleep(0.01)
        except:
            pass


    def down(self):#pushButton9
        try:
            self.radioButton.setChecked(False)#指示灯
            self.pushButton_8.setEnabled(True)
            self.pushButton_10.setEnabled(True)
            value2 = "2"
            sleep(0.05)
            self.port.write('\n'.encode('gbk'))
            self.port.write(value2.encode('gbk'))
            self.port.write('\r\n'.encode('gbk'))
            sleep(0.05)
        except:
            pass
    def left(self):#pushButton5
        try:
            self.radioButton.setChecked(False)  # 指示灯
            self.pushButton_7.setEnabled(True)
            self.pushButton_10.setEnabled(True)
            value3 = "3"
            sleep(0.05)
            self.port.write('\n'.encode('gbk'))
            self.port.write(value3.encode('gbk'))
            self.port.write('\r\n'.encode('gbk'))
            sleep(0.05)
        except:
            pass
    def right(self): #pushButton7
        try:
            self.radioButton.setChecked(False)  # 指示灯
            self.pushButton_5.setEnabled(True)
            self.pushButton_10.setEnabled(True)
            value4 = "4"
            sleep(0.05)
            self.port.write('\n'.encode('gbk'))
            self.port.write(value4.encode('gbk'))
            self.port.write('\r\n'.encode('gbk'))
            sleep(0.05)
        except:
            pass
    def clear_message(self):#恢复所有按键为最初状态
        try:
            self.radioButton.setChecked(False)  # 指示灯
            self.number += 1
            self.pushButton_5.setEnabled(True)
            self.pushButton_7.setEnabled(True)
            self.pushButton_8.setEnabled(True)
            self.pushButton_9.setEnabled(True)
            value5 = "0"
            sleep(0.05)
            self.port.write('\n'.encode('gbk'))
            self.port.write(value5.encode('gbk'))
            self.port.write('\r\n'.encode('gbk'))
            sleep(0.05)
            self.lcdNumber.setProperty("intValue", self.number) #设置LcdNumber的值累加
            print(self.lcdNumber.intValue())
            sleep(0.1)
        except:
            pass

    def pushButton_false(self):
        self.pushButton.setEnabled(False)
        self.pushButton_5.setEnabled(False)
        self.pushButton_7.setEnabled(False)
        self.pushButton_8.setEnabled(False)
        self.pushButton_9.setEnabled(False)
        self.pushButton_10.setEnabled(False)

    def pushButton_ture(self):
        self.pushButton.setEnabled(True)
        self.pushButton_5.setEnabled(True)
        self.pushButton_7.setEnabled(True)
        self.pushButton_8.setEnabled(True)
        self.pushButton_9.setEnabled(True)
        self.pushButton_10.setEnabled(True)
    def Pass(self):
        pass

    def message(self):
        print('已到上限值')
    def exit(self):
        self.port.close()


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    my_pyqt_wigth = Widget() #子窗口定义
    my_pyqt_form = MyQT_From()#主窗口定义
    my_pyqt_form.show()  # 主窗口显示
    sys.exit(app.exec_())

   # try:
     #   sys.exit(app.exec_())
   # except:
      #  os._exit(5)
      #  print("5678$$%%##@@90-")
        #os._exit(0)#直接退出python程序,一般用于线程中退出

```## 标题
以上可以直接运行,注意单片机程序可联系索取

你可能感兴趣的:(python+pyqt5 串口助手)