我有一个使用PyQt创建的GUI。在GUI中,它们是一个按钮,按下时会向客户端发送一些数据。以下是我的代码
class Main(QtGui.QTabWidget, Ui_TabWidget):
def __init__(self):
QtGui.QTabWidget.__init__(self)
self.setupUi(self)
self.pushButton_8.clicked.connect(self.updateActual)
def updateActual():
self.label_34.setText(self.comboBox_4.currentText())
HOST = '127.0.0.1' # The remote host
PORT = 8000 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((displayBoard[str(self.comboBox_4.currentText())], PORT))
except socket.error as e:
err1 = str(self.comboBox_4.currentText()) + " is OFF-LINE"
reply2 = QtGui.QMessageBox.critical(self, 'Error', err1, QtGui.QMessageBox.Ok)
if reply2 == QtGui.QMessageBox.Ok:
pass #stop execution at this point
fileName = str(self.comboBox_4.currentText()) + '.txt'
f = open(fileName)
readLines = f.readlines()
line1 = int(readLines[0])
f.close()
目前,如果用户在QMessageBox中单击“确定”,程序将继续执行代码,以防它们是套接字异常。因此,我的问题是如何以一种干净的方式停止'except'之后的代码执行,这样我的UI不会崩溃,用户可以继续使用它?
答案 0 :(得分:1)
是的,您只需return
阻止if
:
if reply2 == QtGui.QMessageBox.Ok:
return
或者,将代码移至raise socket.error
块时移至else
块:
try: # this might fail
s.connect(...)
except socket.error as e: # what to do if it fails
err1 = ...
reply2 = QtGui.QMessageBox.critical(...)
else: # what to do if it doesn't
with open(fileName) as f:
line1 = int(f.readline().strip())
请注意:
else
选项; with
进行文件处理,它会在块的末尾自动close
;和