PyQt5 訊息框

在本文中,你將學習如何建立 PyQt5 訊息框: 要顯示訊息框,我們需要匯入 QMessageBox

![PyQt5 訊息框](/img/Tutorial/PyQt5/PyQt5 MessageBox.png)

from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox

我們使用方法 QMessageBox.question() 來顯示訊息框。

PyQt5 訊息框程式碼

複製下面的程式碼以顯示訊息框。

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 messagebox - tastones.com'
        self.left = 10
        self.top = 10
        self.width = 320
        self.height = 200
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        buttonReply = QMessageBox.question(self, 'PyQt5 message', "Do you like PyQt5?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if buttonReply == QMessageBox.Yes:
            print('Yes clicked.')
        else:
            print('No clicked.')

        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())

訊息框的更多按鈕

我們來使用 QMessageBox.YesQMessageBox.No 可以輕鬆新增其他選項:

        buttonReply = QMessageBox.question(self, 'PyQt5 message', "Do you want to save?", QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel, QMessageBox.Cancel)
        print(int(buttonReply))
        if buttonReply == QMessageBox.Yes:
            print('Yes clicked.')
        if buttonReply == QMessageBox.No:
            print('No clicked.')
        if buttonReply == QMessageBox.Cancel:
            print('Cancel')

可用的按鈕是:

  • QMessageBox.Cancel

  • QMessageBox.Ok

  • QMessageBox.Help

  • QMessageBox.Open

  • QMessageBox.Save

  • QMessageBox.SaveAll

  • QMessageBox.Discard

  • QMessageBox.Close

  • QMessageBox.Apply

  • QMessageBox.Reset

  • QMessageBox.Yes

  • QMessageBox.YesToAll

  • QMessageBox.No

  • QMessageBox.NoToAll

  • QMessageBox.NoButton

  • QMessageBox.RestoreDefaults

  • QMessageBox.Abort

  • QMessageBox.Retry

  • QMessageBox.Ignore