2016-10-25 46 views
0

當我調用Error Message One(請參閱代碼中的註釋)時,消息很快出現,然後消失。但是,如果我調用錯誤消息二,它看起來只有當我點擊「確定」按鈕時纔會消失。PyQt5:啓動後QMessageBox消失

我該如何解決它,以便錯誤消息一起工作像錯誤消息二?

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() 

回答

3

消息框消失了,因爲你沒有保存對它的引用,所以只要函數返回就會被垃圾回收。

要在你的榜樣解決此問題,使用exec打開消息框,讓他們阻止,直到用戶關閉它們:

msg = QMessageBox() 
... 
msg.exec_() 
+0

太好了!直到現在我還不知道它。 :) 謝謝! –