I am developing a small program that will communicate to serial port. I have developed a GUI using pyQt5.
First of all, the program will read & list the available serial ports. When the user will select any particular port on the list & click on a "Open port" button,the corresponding port will be opened. The Button text will now be changed to "Close port" so the user can close it after use. I am using a state variable to record the current state of the port(portOpen).
The problem happens when the button is clicked & I am trying to save the port open status (1 = Open, 0 = Close) inside the variable by writting portOpen = 1, the program is getting reset. Please take a look where it is getting wrong!
My code is as follows:
import PyQt5
from PyQt5 import QtCore, QtGui, uic, QtWidgets
from PyQt5.QtWidgets import QWidget
import serial
import serial.tools.list_ports
portOpen = 0 #variable to store the port open/close status.If open,value         will be 1
comPorts = list() #create a list named comPorts
mySer = serial.Serial()
mySer.baudrate = 9600
mySer.bytesize = 8
mySer.parity = 'N'
mySer.stopbits = 1
ports = serial.tools.list_ports.comports()
#read the available com ports & save to a list so the list will be like -    [COM0,COM1,COM2---]
def ReadComPorts():
    comPorts.clear() #clear the values of the list
    for port, desc, hwid in sorted(ports):
        comPorts.append(("{}".format(port)))
#These below mentioned part is used to adjust the view of the app to high resolution DPI of windows
if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'):
    PyQt5.QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
if hasattr(QtCore.Qt, 'AA_UseHighDpiPixmaps'):
    PyQt5.QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)
#pyQt5 generated code
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
#read the com ports first
        ReadComPorts()
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(273, 200)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.listWidget = QtWidgets.QListWidget(self.centralwidget)
        self.listWidget.setGeometry(QtCore.QRect(10, 10, 91, 121))
        self.listWidget.setObjectName("listWidget")
#Now,add the read com ports into the list         
        for x in range(len(comPorts)):
            self.listWidget.addItem(comPorts[x])
#When,the an item on list will be clicked,call the item_click function
        self.listWidget.itemClicked.connect(self.item_click)
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(30, 150, 56, 17))
        self.pushButton.setObjectName("pushButton")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
#When the pushbutton will be clicked,call portOpen/close function        
        self.pushButton.clicked.connect(self.PortOpenClose)
    def item_click(self, item):
        comPorts[0] = str(item.text()) #Store the selected port to comPorts  0 location
        print(comPorts[0])
#Open/close the port depending on the current port status
    def PortOpenClose(self):
        if(not(portOpen)):
            try:
                mySer.port = comPorts[0]
                mySer.open()
                self.pushButton.setText("Close Port")
                print('Port opened')
                print(portOpen)
                portOpen = 1 #this line is creating forcing the whole program to close
                                #If i omit this line,port is getting opened properly          
            except:
                print('Error occured')                
    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "Open Port"))
if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
 
     
    