QMessage在类函数中工作正常但不在单独的函数中

时间:2017-06-21 06:12:18

标签: pyqt5 python-3.6

这是我的代码:

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:必须在QWidget之前构建QApplication'

1 个答案:

答案 0 :(得分:0)

您必须首先使用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()