PyQt QMessageBox, you can use to create dialogs. This is a little popup window that you've often seen on your desktop.
It may be a single line message, an "are you sure you want to save?" message or something more advanced.
This messagebox supports all kinds of variations and buttons. In this lesson you'll learn how to create a information dialog window.
Practice now: Test your Python skills with interactive challenges
Dialog
Initial window
Create a window with a button. If you click the button, the dialog will popup.
(This is also where PyQt gets initialized.)
def window():
app = QApplication(sys.argv)
win = QWidget()
button1 = QPushButton(win)
button1.setText("Show dialog!")
button1.move(50,50)
button1.clicked.connect(showDialog)
win.setWindowTitle("Click button")
win.show()
sys.exit(app.exec_())
So lets take a look at showDialog().
Create a dialog
A dialog is created with QMessageBox(). Don't forget to import this from PyQt5.
from PyQt5.QtWidgets import QPushButton
Then use the methods setIcon(), setText(), setWindowTitle() to set the window decoration.
You can configure the dialogs buttons with setStandardButtons().
def showDialog():
msgBox = QMessageBox()
msgBox.setIcon(QMessageBox.Information)
msgBox.setText("Message box pop up window")
msgBox.setWindowTitle("QMessageBox Example")
msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
msgBox.buttonClicked.connect(msgButtonClick)
returnValue = msgBox.exec()
if returnValue == QMessageBox.Ok:
print('OK clicked')

Downloadable code
You can copy and paste the code below on your own computer, to test how it works.
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
def window():
app = QApplication(sys.argv)
win = QWidget()
button1 = QPushButton(win)
button1.setText("Show dialog!")
button1.move(50,50)
button1.clicked.connect(showDialog)
win.setWindowTitle("Click button")
win.show()
sys.exit(app.exec_())
def showDialog():
msgBox = QMessageBox()
msgBox.setIcon(QMessageBox.Information)
msgBox.setText("Message box pop up window")
msgBox.setWindowTitle("QMessageBox Example")
msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
msgBox.buttonClicked.connect(msgButtonClick)
returnValue = msgBox.exec()
if returnValue == QMessageBox.Ok:
print('OK clicked')
def msgButtonClick(i):
print("Button clicked is:",i.text())
if __name__ == '__main__':
window()
Practice now: Test your Python skills with interactive challenges
Practice now: Test your Python skills with interactive challenges