PyQt5:QMessageBox启动后消失

Ram*_*elm 1 python pyqt qmessagebox pyqt5

当我调用错误消息一(请参阅代码中的注释)时,该消息很快出现然后消失。但是,如果我调用错误消息二,它就会出现,并且只有在我单击“确定”按钮时才会消失。

如何修复它以使错误消息一像错误消息二一样工作?

    try:
        connection = pymysql.connect(host = 'localhost',
            user = 'root',
            db = 'Telephon Register',
            cursorclass = pymysql.cursors.DictCursor)  
        cur = connection.cursor()

        if number!= "":
            cur.execute("SELECT Number FROM formen WHERE Telephonebook = " + self.number.text() )
            result = cur.fetchone()

            if len(result) == 0:
                cur.execute("INSERT INTO formen VALUES(" + self.number.text())  
                connection.commit()
            else:
                print("The number " + number+ " already exists.")
        else:
            print("You have not typed a number!")
            msg = QMessageBox()  #EXCEPTION MESSAGE ONE
            msg.setIcon(2)
            msg.setText("Some Text")
            msg.setInformativeText("Some informative text")
            msg.setWindowTitle("Error")
            msg.show()

        connection.close()
    except:
        print("Connection does not work!")
        msg = QMessageBox()     # EXCEPTION MESSAGE TWO
        msg.setIcon(3)
        msg.setText("Some Text")
        msg.setInformativeText("Some message")
        msg.setWindowTitle("Error")
        msg.show()
Run Code Online (Sandbox Code Playgroud)

ekh*_*oro 6

消息框消失是因为您没有保留对它的引用,因此函数返回后它就会被垃圾收集。

要在您的示例中解决此问题,请使用 打开消息框exec,以便它们会阻塞,直到用户关闭它们:

msg = QMessageBox()
...
msg.exec_() 
Run Code Online (Sandbox Code Playgroud)