原文: https://pythonspot.com/pyqt5-messagebox/

在本文中,您将学习如何创建 PyQt5 消息框:

PyQt5 消息框 - 图1

为了显示一个消息框,我们需要导入QMessageBox

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

我们使用方法QMessageBox.question()显示消息框。

PyQt5 消息框代码

复制以下代码以显示消息框。

  1. import sys
  2. from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox
  3. from PyQt5.QtGui import QIcon
  4. from PyQt5.QtCore import pyqtSlot
  5. class App(QWidget):
  6. def __init__(self):
  7. super().__init__()
  8. self.title = 'PyQt5 messagebox - pythonspot.com'
  9. self.left = 10
  10. self.top = 10
  11. self.width = 320
  12. self.height = 200
  13. self.initUI()
  14. def initUI(self):
  15. self.setWindowTitle(self.title)
  16. self.setGeometry(self.left, self.top, self.width, self.height)
  17. buttonReply = QMessageBox.question(self, 'PyQt5 message', "Do you like PyQt5?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
  18. if buttonReply == QMessageBox.Yes:
  19. print('Yes clicked.')
  20. else:
  21. print('No clicked.')
  22. self.show()
  23. if __name__ == '__main__':
  24. app = QApplication(sys.argv)
  25. ex = App()
  26. sys.exit(app.exec_())

消息框的更多按钮

考虑到我们使用QMessageBox.YesQMessageBox.No。 我们可以轻松添加其他选项:

  1. buttonReply = QMessageBox.question(self, 'PyQt5 message', "Do you want to save?", QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel, QMessageBox.Cancel)
  2. print(int(buttonReply))
  3. if buttonReply == QMessageBox.Yes:
  4. print('Yes clicked.')
  5. if buttonReply == QMessageBox.No:
  6. print('No clicked.')
  7. if buttonReply == QMessageBox.Cancel:
  8. 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

下载 PyQT5 示例