如何在PyQT5中建立串行连接

时间:2017-06-26 10:32:00

标签: python qt user-interface pyqt pyserial

我是python的新手。我正在使用python 3.6(pyqt5)在Qt中开发GUI。我有一个连接按钮,与设备建立串行连接。现在GUI还有其他按钮。但是只有按下连接按钮并建立了串行连接,它们才能工作。在所有其他时间,它应该发布消息'Device not connected'。这是代码的一部分:

import serial, time
import sys
import PyQt5
from PyQt5.QtWidgets import *
import mainwindow_auto
class MainWindow(QMainWindow, mainwindow_auto.Ui_MainWindow):
    def __init__(self):
        #define gui actions here
        super(self.__class__, self).__init__()
        self.setupUi(self)
        self.constat=0

        self.plus_y_button.clicked.connect(self.moveplusy)   
        self.connect_button.clicked.connect(self.connect_printer)

    def connect_printer(self):

        port=str(self.port_sel_box.currentText())
        baudrate=str(self.baud_sel_box.currentText())

        try:
            ser = serial.Serial(port, baudrate)
            self.log_box.append('Connecting to printer....\nPort selected :'+self.port_sel_box.currentText()+'\nBaud Rate :'+self.baud_sel_box.currentText())

        except serial.serialutil.SerialException:
            self.log_box.append('No device available....Please connect a device')
    def moveplusy(self):
       if(ser.isOpen()==true):

           print('moving Y by +1')
           self.log_box.append('moving Y by +1')
       else:
           print('No device available')

这只是代码的一部分,我没有在代码中包含所有小部件,只包括相关部分。当我运行代码时,gui窗口打开,但是当我按下plus_y_button python时崩溃。一种方法是在构造函数中进行串行连接,但我希望只有在按下connect_button时才能进行串行连接。这是按下plus_y_button

时发生的情况的屏幕截图

screenshot

关于如何解决它的任何想法?

1 个答案:

答案 0 :(得分:0)

在函数“connect_printer”中,您在本地定义变量“ser”,然后在函数完成时将其销毁。为了在函数“moveplusy”中使用“ser”,你需要将它定义为类的成员(例如self.ser)。此外,“True”应该在函数中大写。

import serial, time
import sys
import PyQt5
from PyQt5.QtWidgets import *
import mainwindow_auto
class MainWindow(QMainWindow, mainwindow_auto.Ui_MainWindow):
    def __init__(self):
        #define gui actions here
        super(self.__class__, self).__init__()
        self.setupUi(self)
        self.constat=0

        self.plus_y_button.clicked.connect(self.moveplusy)   
        self.connect_button.clicked.connect(self.connect_printer)

    def connect_printer(self):

        port=str(self.port_sel_box.currentText())
        baudrate=str(self.baud_sel_box.currentText())

        try:
            self.ser = serial.Serial(port, baudrate)
            self.log_box.append('Connecting to printer....\nPort selected :'+self.port_sel_box.currentText()+'\nBaud Rate :'+self.baud_sel_box.currentText())

        except serial.serialutil.SerialException:
            self.log_box.append('No device available....Please connect a device')
    def moveplusy(self):
       if self.ser.isOpen():

           print('moving Y by +1')
           self.log_box.append('moving Y by +1')
       else:
           print('No device available')