用pyside6写一个带界面的串口工具
时间: 2023-11-06 12:04:18 浏览: 422
Python写串口工具
好的,下面是一个基于 PySide6 的串口工具示例代码,它包含一个简单的界面和串口通信功能:
```python
import sys
import serial
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QLineEdit, QPushButton, QTextEdit, QVBoxLayout, QWidget
class SerialTool(QMainWindow):
def __init__(self):
super().__init__()
self.serial = None
# 创建界面控件
self.port_label = QLabel('Port')
self.port_edit = QLineEdit('/dev/ttyUSB0')
self.baudrate_label = QLabel('Baudrate')
self.baudrate_edit = QLineEdit('9600')
self.connect_button = QPushButton('Connect')
self.disconnect_button = QPushButton('Disconnect')
self.send_button = QPushButton('Send')
self.recv_text = QTextEdit()
# 设置控件属性
self.recv_text.setReadOnly(True)
# 创建布局
vbox = QVBoxLayout()
vbox.addWidget(self.port_label)
vbox.addWidget(self.port_edit)
vbox.addWidget(self.baudrate_label)
vbox.addWidget(self.baudrate_edit)
vbox.addWidget(self.connect_button)
vbox.addWidget(self.disconnect_button)
vbox.addWidget(self.recv_text)
vbox.addWidget(self.send_button)
# 创建主窗口
central_widget = QWidget(self)
central_widget.setLayout(vbox)
self.setCentralWidget(central_widget)
# 连接信号槽
self.connect_button.clicked.connect(self.connect_serial)
self.disconnect_button.clicked.connect(self.disconnect_serial)
self.send_button.clicked.connect(self.send_data)
def connect_serial(self):
# 获取串口参数
port = self.port_edit.text()
baudrate = int(self.baudrate_edit.text())
# 打开串口
self.serial = serial.Serial(port, baudrate, timeout=1)
if self.serial.isOpen():
self.recv_text.append('Serial port connected')
def disconnect_serial(self):
# 关闭串口
if self.serial:
self.serial.close()
self.recv_text.append('Serial port disconnected')
def send_data(self):
# 发送数据
if self.serial and self.serial.isOpen():
data = self.send_edit.text()
self.serial.write(data.encode('utf-8'))
def closeEvent(self, event):
# 关闭窗口时断开串口
if self.serial and self.serial.isOpen():
self.serial.close()
super().closeEvent(event)
if __name__ == '__main__':
app = QApplication(sys.argv)
tool = SerialTool()
tool.show()
sys.exit(app.exec())
```
这段代码创建了一个带有串口连接、断开、发送和接收功能的界面,你可以根据实际需求修改代码,比如更改界面布局、增加其他控件等。同时,你需要在系统中安装 PySide6 库才能运行这个程序。
阅读全文