QMessage 在 class 函数中运行良好,但在单独的函数中运行不正常

QMessage is working fine in a class function but not in separate function

这是我的代码:

def er():
    print("connection error")
    from PyQt5.QtWidgets import QMessageBox
    msg = QMessageBox()
    msg.setIcon(QMessageBox.Information)
    msg.setText("Some text ")
    msg.setInformativeText("info text")
    msg.setWindowTitle("title")
    msg.setStandardButtons(QMessageBox.Ok)
    retval = msg.exec_()
    print(retval)
if __name__ == '__main__':

    mac = (':'.join(['{:02x}'.format((getnode() >> i) & 0xff) for i in range(0,8 * 6, 8)][::-1]))

    if mac == 'b8:e8:56:24:96:30':
        print("OK")
        some_function
    else:
        er()

错误是'QWidget: Must construct a QApplication before a QWidget'

您必须首先使用 QApplication 初始化 qt 事件循环,如错误消息所述

def er():
    print("connection error")
    from PyQt5.QtWidgets import QMessageBox,QApplication
    import sys
    app = QApplication(sys.argv)

    msg = QMessageBox()
    msg.setIcon(QMessageBox.Information)
    msg.setText("Some text ")
    msg.setInformativeText("info text")
    msg.setWindowTitle("title")
    msg.setStandardButtons(QMessageBox.Ok)
    retval = msg.exec_()
    print(retval)


if __name__ == '__main__':

    mac = (':'.join(['{:02x}'.format((getnode() >> i) & 0xff) for i in range(0, 8 * 6, 8)][::-1]))

    if mac == 'b8:e8:56:24:96:30':
       print("OK")
       some_function
    else:
       er()