Contents

本文根据pythonspot英文教程编写,并加入了搜集的其他材料,by kowen

首先要引入 QmessageBox类:

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

然后调用QMessageBox.question()来显示消息窗口。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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 - pythonspot.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.Yes和QMessageBox.No可以方便的添加需要的按钮

1
2
3
4
5
6
7
8
9
10
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')

PyQt5提供了丰富的按钮可供选择:

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
Contents