制作一个串口助手 | python + pyqt5
以下是一个使用Python和PyQt5制作的简易串口助手的代码示例:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QLabel, QPushButton, QMessageBox
from PyQt5.QtSerialPort import QSerialPort, QSerialPortInfo
class SerialPortTerminal(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('串口助手')
self.port = QSerialPort()
self.initUI()
def initUI(self):
# 列出所有可用串口并显示
port_info_list = QSerialPortInfo().availablePorts()
self.port_list = [x.portName() for x in port_info_list]
self.port_label = QLabel('串口列表:')
self.port_label.setMinimumWidth(150)
self.port_combo = QComboBox()
self.port_combo.addItems(self.port_list)
# 打开和关闭串口按钮
self.open_btn = QPushButton('打开串口')
self.open_btn.clicked.connect(self.open_port)
self.close_btn = QPushButton('关闭串口')
self.close_btn.clicked.connect(self.close_port)
self.close_btn.setEnabled(False)
# 布局
layout = QVBoxLayout()
layout.addWidget(self.port_label)
layout.addWidget(self.port_combo)
layout.addWidget(self.open_btn)
layout.addWidget(self.close_btn)
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
def open_port(self):
port_name = self.port_combo.currentText()
self.port.setPortName(port_name)
if not self.port.open(QIODevice.ReadWrite):
QMessageBox.critical(self, '错误', '无法打开串口')
return
self.open_btn.setEnabled(False)
self.close_btn.setEnabled(True)
def close_port(self):
self.port.close()
self.open_btn.setEnabled(True)
self.close_btn.setEnabled(False)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = SerialPortTerminal()
ex.
评论已关闭