python logo

pyqt5 messagebox

Python hosting: Host, run, and code Python in the cloud!

In this article you will learn how to create a PyQt5 messagebox:

A message box is a class to show a small dialog with an ordinary message, an information message, or a question and it can confirm one or two choices.

A message box can be created using the class QMessageBox. This class provides a modal dialog with a short text, an icon, and buttons. The class has method show() display a message box and return immediately.


To show a messagebox we need to import QMessageBox.

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

We use the method QMessageBox.question() to display the messagebox.

Related course: Create GUI Apps with PyQt5

PyQt5 messagebox code
Copy the code below to display a messagebox.

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):
self.title = 'PyQt5 messagebox -'
self.left = 10 = 10
self.width = 320
self.height = 200

def initUI(self):
self.setGeometry(self.left,, 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.')
print('No clicked.')

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

More buttons for a messagebox
Take into account we use QMessageBox.Yes and QMessageBox.No. We can easily add other options:

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

The available buttons are:

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

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples


Leave a Reply: