python – PyQt5 – 自动化串行模块
作者:互联网
我试图自动化串行连接而不点击按钮.当gui加载时,应立即读取串行并按间隔刷新而不使用鼠标触发任何按钮(即自动读入和更新).
这怎么可能?请参阅下面的脚本和GUI ..
import schedule
import serial
import sys
from PyQt5 import uic, QtWidgets
qtCreatorFile = "gui.ui"
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
estudiantes = [' ',' ',' ',' ']
ser = serial.Serial('COM9', baudrate=9600, timeout=1)
class MyApp(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
self.Boton.clicked.connect(self.ingresos)
#self.ingresos()
def ingresos(self):
dato = ser.readline().decode('ascii')
#datos = (self.Box4.toPlainText())
#dato = str(datos)
estudiantes.insert(0,dato)
estudiantes.pop()
self.Box1.setText(estudiantes[0])
self.Box2.setText(estudiantes[1])
self.Box3.setText(estudiantes[2])
self.Box4.setText(estudiantes[3])
#self.Box1.setText("estudiantes")
# =============================================
def job():
# print("I'm working...")
dato = ser.readline().decode('ascii')
#datos = (self.Box4.toPlainText())
#dato = str(datos)
estudiantes.insert(0,dato)
estudiantes.pop()
self.Box1.setText(estudiantes[0])
self.Box2.setText(estudiantes[1])
self.Box3.setText(estudiantes[2])
self.Box4.setText(estudiantes[3])
#self.Box1.setText("estudiantes")
# .......................
schedule.every(0.05).minutes.do(job)
while True:
schedule.run_pending()
time.sleep(1)
# .... Time definition ....
# 0.05 = 05 Seconds
# 0.50 = 50 Seconds
# 5.00 = 05 Minutes
# =============================================
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())
PyQt5 GUI .ui文件是HERE ….
解决方法:
Qt中的一个基本规则是不应该从主要线程以外的线程更新GUI,这称为GUI线程.有几个选项,例如通过信号将数据发送到主线程,或使用带有QThreadPool的QRunnable,如下所示:
码:
qtCreatorFile = "gui.ui"
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
estudiantes = [' ',' ',' ',' ']
class SerialRunnable(QtCore.QRunnable):
def __init__(self, w):
QtCore.QRunnable.__init__(self)
self.w = w
self.ser = serial.Serial('COM9', baudrate=9600, timeout=1)
def run(self):
while True:
dato = self.ser.readline().decode('ascii')
if dato != "":
QtCore.QMetaObject.invokeMethod(self.w, "setValues",
QtCore.Qt.QueuedConnection,
QtCore.Q_ARG(str, dato))
QtCore.QThread.msleep(10)
class MyApp(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
self.setupUi(self)
runnable = SerialRunnable(self)
QtCore.QThreadPool.globalInstance().start(runnable)
@QtCore.pyqtSlot(str)
def setValues(self, dato):
estudiantes.insert(0,dato)
estudiantes.pop()
self.Box1.setText(estudiantes[0])
self.Box2.setText(estudiantes[1])
self.Box3.setText(estudiantes[2])
self.Box4.setText(estudiantes[3])
标签:pyserial,pyqt5,python,python-3-x,pyqt 来源: https://codeday.me/bug/20190926/1819938.html