When creating a Python GUI, you may want to show the message box QMessageBox at some point. The QMessageBox is a dialog that shows an informational message. It can optionally ask the user to click any of the buttons that show inside it.

Pyqt comes with messagebox support in both PyQt4 and PyQt5. The class to be used is QMessageBox.

In this tutorial you’ll learn how to show a message box on buton click.

Related course: Create PyQt Desktop Appications with Python (GUI)

QMessageBox example

The first thing to do, if you haven’t done so, is to install the PyQt GUI module.

Import QMessageBox from the PyQt5 widgets

from PyQt5.QtWidgets import QMessageBox

A messagebox can easily be added to the window using the code:

QMessageBox.about(self, "Title", "Message")

qt message box

The code below create a window with a button. If you click on the button it shows a messagebox.
The messagebox is created with QMessageBox.about(self,title,message). This sets the window title and message too.

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtCore import QSize

class MainWindow(QMainWindow):
def __init__(self):

self.setMinimumSize(QSize(300, 200))
self.setWindowTitle("PyQt messagebox example - pythonprogramminglanguage.com")

pybutton = QPushButton('Show messagebox', self)
pybutton.move(50, 50)

def clickMethod(self):
QMessageBox.about(self, "Title", "Message")

if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = MainWindow()
sys.exit( app.exec_() )

Related course: Create PyQt Desktop Appications with Python (GUI)

QMessageBox types

There are several types of icons that can be set in PyQt messagebox, they are: information, question, warning and critical.

Depending on the type of message box you want to show, you can change it to the one you need for your application.


QMessageBox buttons

You can set the default buttons shown in a message box. You can do that with the method setStandrdButtons(), then add the buttons you need.

msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)

It comes with a whole range of buttons:

  • QMessageBox.Ok
  • QMessageBox.Open
  • QMessageBox.Save
  • QMessageBox.Cancel
  • QMessageBox.Close
  • QMessageBox.Yes
  • QMessageBox.No
  • QMessageBox.Abort
  • QMessageBox.Retry
  • QMessageBox.Ignore

You can test which button is clicked by capturing its return value:

ret = QMessageBox.question(self, 'MessageBox', "Click a button", QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel, QMessageBox.Cancel)

if ret == QMessageBox.Yes:
print('Button QMessageBox.Yes clicked.')

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

Download PyQt Examples