用pyqt5写一个能显示获取的串口CMO7的界面
时间: 2023-12-04 17:02:52 浏览: 146
好的,下面是一个用 PyQt5 编写的串口监控界面的示例代码。需要安装 pyserial 库和 PyQt5 库。
```python
import sys
import serial
from PyQt5 import QtCore, QtWidgets
class SerialMonitor(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.serial_port = serial.Serial()
self.serial_port.baudrate = 9600
self.serial_port.timeout = 0.1
layout = QtWidgets.QVBoxLayout()
self.setLayout(layout)
self.open_button = QtWidgets.QPushButton('Open')
self.open_button.clicked.connect(self.open_serial_port)
layout.addWidget(self.open_button)
self.close_button = QtWidgets.QPushButton('Close')
self.close_button.setEnabled(False)
self.close_button.clicked.connect(self.close_serial_port)
layout.addWidget(self.close_button)
self.text_edit = QtWidgets.QTextEdit()
self.text_edit.setReadOnly(True)
layout.addWidget(self.text_edit)
self.serial_timer = QtCore.QTimer()
self.serial_timer.timeout.connect(self.read_serial_data)
def open_serial_port(self):
port_name = 'COM7' # Replace with your serial port name
try:
self.serial_port.port = port_name
self.serial_port.open()
except serial.SerialException as e:
QtWidgets.QMessageBox.critical(self, 'Error', str(e))
return
self.open_button.setEnabled(False)
self.close_button.setEnabled(True)
self.serial_timer.start(100)
def close_serial_port(self):
self.serial_timer.stop()
self.serial_port.close()
self.open_button.setEnabled(True)
self.close_button.setEnabled(False)
def read_serial_data(self):
while self.serial_port.in_waiting > 0:
data = self.serial_port.read(1)
self.text_edit.insertPlainText(data.decode())
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = SerialMonitor()
window.show()
sys.exit(app.exec_())
```
你可以根据自己的需求修改代码中的串口名称、波特率等参数。
阅读全文
相关推荐


















