我正在开发一个可以与串行端口通信的小程序。我已经使用pyQt5开发了一个GUI。
首先,程序将读取并列出可用的串行端口。当用户在列表中选择任何特定端口并单击"Open port"
按钮时,将打开相应的端口。按钮文本现在将更改为"Close port"
,以便用户在使用后可以将其关闭。我正在使用状态变量来记录端口(portOpen
)的当前状态。
单击按钮时出现问题,并且我试图通过以下方式在变量内保存端口打开状态(1
= Open
,0
= Close
)写portOpen
= 1,程序将被重置。请看看哪里出了问题!
我的代码如下:
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_())
答案 0 :(得分:0)
我已经在评论中回答了,但是我没有时间发表冗长的解释为什么我的建议有效:
问题在于Python如何处理全局变量和局部变量。
基本上,如果不需要全局变量,则应避免使用它们。在许多语言中,意外更改全局变量的值太容易了,因此Python使我们明确声明要更改它-使用global
关键字。
如果仅读取全局变量,则代码有效,因为Python按顺序查找变量:不是局部变量?进一步检查...依此类推,直到达到全局范围。
但是在添加了赋值(没有global
关键字)的情况下,Python在局部范围内看到了该变量,并假定该变量在整个函数中都是局部的-并使其失败,因为该变量是从赋值之前读取的-是print(portOpen)
失败了,而不是分配本身(!)。 (非常感谢,他们是如此亲密,以至于错误消息意外地得到了帮助。)
global portOpen
向解释器显示该赋值未创建新的局部变量,因此所有读取和赋值开始正常工作。