In this article, we will discuss the Message Box Widget of the PyQT5 module. It is used to display the message boxes. PyQt5 is a library used to create GUI using the Qt GUI framework. Qt is originally written in C++ but can be used in Python. The latest version of PyQt5 can be installed using the command:
pip install PyQt5
What is a Message Box?
Message Boxes are usually used for declaring a small piece of information to the user. It gives users a pop-up box, that cannot be missed, to avoid important errors and information being missed by the users and in some cases, the user cannot continue without acknowledging the message box.

Based on the applications there are four types of message boxes. The following is the syntax for creating a message box. For any of the boxes, instantiation needs to be done.
Syntax:
msg_box_name = QMessageBox()
Now according to the requirement an appropriate message box is created.
Types of Message Box
Information Message Box
This type of message box is used when related information needs to be passed to the user.
Syntax:
msg_box_name.setIcon(QMessageBox.Information)

Question Message Box
This message box is used to get an answer from a user regarding some activity or action to be performed.
Syntax:
msg_box_name.setIcon(QMessageBox.Question)

Warning Message Box
This triggers a warning regarding the action the user is about to perform.
Syntax:
msg_box_name.setIcon(QMessageBox.Warning)

Critical Message Box
This is often used for getting the user’s opinion for a critical action.
Syntax:
msg_box_name.setIcon(QMessageBox.Critical)

Creating a simple Message Box using PyQt5
Now to create a program that produces a message box first import all the required modules, and create a widget with four buttons, on clicking any of these a message box will be generated.
Now for each button associate a message box that pops when the respective button is clicked. For this first, instantiate a message box and add a required icon. Now set appropriate attributes for the pop that will be generated. Also, add buttons to deal with standard mechanisms.
Given below is the complete implementation.
Program:
Python
import sys
from PyQt5.QtWidgets import *
def window():
app = QApplication(sys.argv)
w = QWidget()
b1 = QPushButton(w)
b1.setText("Information")
b1.move(45, 50)
b2 = QPushButton(w)
b2.setText("Warning")
b2.move(150, 50)
b3 = QPushButton(w)
b3.setText("Question")
b3.move(50, 150)
b4 = QPushButton(w)
b4.setText("Critical")
b4.move(150, 150)
b1.clicked.connect(show_info_messagebox)
b2.clicked.connect(show_warning_messagebox)
b3.clicked.connect(show_question_messagebox)
b4.clicked.connect(show_critical_messagebox)
w.setWindowTitle("PyQt MessageBox")
w.show()
sys.exit(app.exec_())
def show_info_messagebox():
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText("Information ")
msg.setWindowTitle("Information MessageBox")
msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
retval = msg.exec_()
def show_warning_messagebox():
msg = QMessageBox()
msg.setIcon(QMessageBox.Warning)
msg.setText("Warning")
msg.setWindowTitle("Warning MessageBox")
msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
retval = msg.exec_()
def show_question_messagebox():
msg = QMessageBox()
msg.setIcon(QMessageBox.Question)
msg.setText("Question")
msg.setWindowTitle("Question MessageBox")
msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
retval = msg.exec_()
def show_critical_messagebox():
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setText("Critical")
msg.setWindowTitle("Critical MessageBox")
msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
retval = msg.exec_()
if __name__ == '__main__':
window()
Output

In this article, we will discuss the Message Box Widget of the PyQT5 module. It is used to display the message boxes. PyQt5 is a library used to create GUI using the Qt GUI framework. Qt is originally written in C++ but can be used in Python. The latest version of PyQt5 can be installed using the command:
pip install PyQt5
What is a Message Box?
Message Boxes are usually used for declaring a small piece of information to the user. It gives users a pop-up box, that cannot be missed, to avoid important errors and information being missed by the users and in some cases, the user cannot continue without acknowledging the message box.

Based on the applications there are four types of message boxes. The following is the syntax for creating a message box. For any of the boxes, instantiation needs to be done.
Syntax:
msg_box_name = QMessageBox()
Now according to the requirement an appropriate message box is created.
Types of Message Box
Information Message Box
This type of message box is used when related information needs to be passed to the user.
Syntax:
msg_box_name.setIcon(QMessageBox.Information)

Question Message Box
This message box is used to get an answer from a user regarding some activity or action to be performed.
Syntax:
msg_box_name.setIcon(QMessageBox.Question)

Warning Message Box
This triggers a warning regarding the action the user is about to perform.
Syntax:
msg_box_name.setIcon(QMessageBox.Warning)

Critical Message Box
This is often used for getting the user’s opinion for a critical action.
Syntax:
msg_box_name.setIcon(QMessageBox.Critical)

Creating a simple Message Box using PyQt5
Now to create a program that produces a message box first import all the required modules, and create a widget with four buttons, on clicking any of these a message box will be generated.
Now for each button associate a message box that pops when the respective button is clicked. For this first, instantiate a message box and add a required icon. Now set appropriate attributes for the pop that will be generated. Also, add buttons to deal with standard mechanisms.
Given below is the complete implementation.
Program:
Python
import sys
from PyQt5.QtWidgets import *
def window():
app = QApplication(sys.argv)
w = QWidget()
b1 = QPushButton(w)
b1.setText("Information")
b1.move(45, 50)
b2 = QPushButton(w)
b2.setText("Warning")
b2.move(150, 50)
b3 = QPushButton(w)
b3.setText("Question")
b3.move(50, 150)
b4 = QPushButton(w)
b4.setText("Critical")
b4.move(150, 150)
b1.clicked.connect(show_info_messagebox)
b2.clicked.connect(show_warning_messagebox)
b3.clicked.connect(show_question_messagebox)
b4.clicked.connect(show_critical_messagebox)
w.setWindowTitle("PyQt MessageBox")
w.show()
sys.exit(app.exec_())
def show_info_messagebox():
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText("Information ")
msg.setWindowTitle("Information MessageBox")
msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
retval = msg.exec_()
def show_warning_messagebox():
msg = QMessageBox()
msg.setIcon(QMessageBox.Warning)
msg.setText("Warning")
msg.setWindowTitle("Warning MessageBox")
msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
retval = msg.exec_()
def show_question_messagebox():
msg = QMessageBox()
msg.setIcon(QMessageBox.Question)
msg.setText("Question")
msg.setWindowTitle("Question MessageBox")
msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
retval = msg.exec_()
def show_critical_messagebox():
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setText("Critical")
msg.setWindowTitle("Critical MessageBox")
msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
retval = msg.exec_()
if __name__ == '__main__':
window()
Output

5 ответов
Qt включает в себя класс диалога для сообщений об ошибках QErrorMessage который вы должны использовать, чтобы ваш диалог соответствовал системным стандартам. Чтобы показать диалог, просто создайте объект диалога, затем вызовите .showMessage(). Например:
error_dialog = QtWidgets.QErrorMessage()
error_dialog.showMessage('Oh no!')
Вот минимальный рабочий пример скрипта:
import PyQt5
from PyQt5 import QtWidgets
app = QtWidgets.QApplication([])
error_dialog = QtWidgets.QErrorMessage()
error_dialog.showMessage('Oh no!')
app.exec_()
mfitzp
24 окт. 2016, в 19:04
Поделиться
Все вышеперечисленные варианты не работали для меня, используя Komodo Edit 11.0. Просто вернул «1» или, если не был реализован «-1073741819».
Полезным для меня было: решение Ванлока.
def my_exception_hook(exctype, value, traceback):
# Print the error and traceback
print(exctype, value, traceback)
# Call the normal Exception hook after
sys._excepthook(exctype, value, traceback)
sys.exit(1)
# Back up the reference to the exceptionhook
sys._excepthook = sys.excepthook
# Set the exception hook to our wrapping function
sys.excepthook = my_exception_hook
ZF007
13 нояб. 2017, в 20:15
Поделиться
Следующее должно работать:
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setText("Error")
msg.setInformativeText(e)
msg.setWindowTitle("Error")
Это не тот же тип сообщения (разные GUI), но довольно близко. e — выражение для ошибки в python3
Надеюсь, что это помогло,
Narusan
24 окт. 2016, в 18:21
Поделиться
Не забудьте вызвать .exec() _ для отображения ошибки:
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setText("Error")
msg.setInformativeText('More information')
msg.setWindowTitle("Error")
msg.exec_()
NShiell
08 янв. 2019, в 12:47
Поделиться
Чтобы показать окно сообщения, вы можете вызвать это определение:
from PyQt5.QtWidgets import QMessageBox
def clickMethod(self):
QMessageBox.about(self, "Title", "Message")
Karam Qusai
17 апр. 2019, в 10:06
Поделиться
Ещё вопросы
- 1Как я могу усреднить каждые 5 строк конкретного столбца и выбрать последние данные из другого столбца в Pandas
- 1Как добавить ускорение к скорости?
- 1Как я могу постепенно и плавно изменять размер PictureBox? (в winforms, c #, visual studio 2013)
- 1Eclipse — ButtonCLick -> новый экран с текстом?
- 1Асинхронный обратный вызов функции mongodb
- 1Android Alarm Manager
- 0Почему это правильно для размера буфера мало при использовании sprintf в C ++
- 1Нажмите кнопку, чтобы запустить функцию JavaScript без JQuery
- 0Как я могу сделать HTML-страницу, которая отлично работает в веб и мобильных приложениях
- 0Проблемы с $ scope. $ Apply () во вложенных обратных вызовах
- 0Как вставить значение эха в переменную? [Дубликат]
- 1Python: переупорядочить словарь по первой половине / части ключа
- 1Добавление изображений в ListView
- 0Mysql Неизвестная переменная ошибка
- 0Где я могу разместить HTML-шаблон для Angular UI Modal?
- 1Обновить существующие записи базы данных C # VS2010
- 1Проблема с Android jAudioTagger — чтение mp3 файла — VerifyError
- 1Конвертировать точки Тип данных vtkUnstructuredGrid
- 1Проблема при отправке объекта JSON с помощью BeanShell PreProcessor
- 0Проверьте, находится ли позиция / символ внутри тега HTML
- 0jQuery разборный div, сворачивание 2-ой div
- 0директива angularjs не соответствует области действия. $ watch
- 0Ошибка в итерации / объектных массивах php
- 0Навигация по слайдеру кодирования
- 0Как обрабатывать куки при обновлении приложения?
- 0получить обоих слизней из одинаковых категорий
- 1Проверка, было ли прочитано новое SMS
- 0почему я не могу ввести директиву в мои тесты
- 0объединить две таблицы в файле php
- 0base64_decode не работает для PHP
- 1Добавить таймер для изображений в javafx
- 1очистить очередь rabbitmq с помощью весеннего шаблона amqp?
- 0CodeIgniter 3 — неагрегированная группа столбцов по
- 1Gulp: Uglifying Bootstrap 4 js-файлов
- 1Реактивность в пользовательских виджетах
- 1ValueError: Ошибка при проверке ввода: ожидалось, что gru_5_input будет иметь форму (None, None, 10), но получил массив с формой (1, 4, 1)
- 1UserError сработал со значением 0
- 0Как я могу конвертировать мой BLOB-файл в WAV-файл?
- 1попробуйте выполнить задачу n раз, прежде чем выдать ошибку [duplicate]
- 1Избегайте вызова BeginInvoke () из объектов ViewModel в многопоточном приложении c # MVVM
- 0вставка данных таблицы в базу данных имеют одинаковые имена
- 0UTF8 с file_get_contents ()
- 0фокусируемый прокручиваемый div в позицию
- 0Как создать таблицу в базе данных MySQL через приложение Android?
- 1Как заставить поля ввода текста двигаться вверх при наличии экранной клавиатуры
- 1Как случайным образом раскрасить сетку (каждая строка случайным цветом)
- 1Невозможно установить ItemsSource для XamComboEditor в XamDataGrid
- 0Получить метаданные GPS из изображения в Dropbox с помощью PHP
- 0нужно применить без переноса и отключить правый контроль карусели в Angularjs ui carousel
- 1Невозможно вернуть объект [], приведенный как String []
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")

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):
QMainWindow.__init__(self)
self.setMinimumSize(QSize(300, 200))
self.setWindowTitle("PyQt messagebox example - pythonprogramminglanguage.com")
pybutton = QPushButton('Show messagebox', self)
pybutton.clicked.connect(self.clickMethod)
pybutton.resize(200,64)
pybutton.move(50, 50)
def clickMethod(self):
QMessageBox.about(self, "Title", "Message")
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
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.
msg.setIcon(QMessageBox.Information)
msg.setIcon(QMessageBox.Question)
msg.setIcon(QMessageBox.Warning)
msg.setIcon(QMessageBox.Critical)
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
This article covers the PyQt5 widget, QMessageBox.
QMessageBox is a useful PyQt5 widget used to create dialogs. These dialogs can be used for a variety of purposes and customized in many ways to display different messages and buttons.
In this PyQt5 tutorial you’ll also find a complete list of all methods, buttons types and options for the QMessageBox widget.
Creating a QMessageBox
Below we are just going to create a simple QMessageBox widget. It’s going to be a bare-bone messagebox with no added features or customization.
msg = QMessageBox(win)
msg.setWindowTitle("Message Box")
msg.setText("This is some random text")
x = msg.exec_()
And below is the output. If you want to display a simple message on screen, this is the way to do so.

Now compare this simple messagebox to the advanced and feature-rich message-boxes we are going to create below.
QMessageBox Icons
QMessageBox has 4 different types of icons that can be used by calling the setIcon() function. Decide which one to use depending on type of message you wish to display.
- QMessageBox.Question
- QMessageBox.Information
- QMessageBox.Warning
- QMessageBox.Critical
All you have to do is pass one of the above to the setIcon() function as shown below.
msg.setIcon(QMessageBox.Question)
Below are all four different messages that can be displayed.

QMessageBox Buttons
Uptil now we’ve been using the default “OK” button that QMessageBox offers. However, there are actually over a dozen different buttons that QMessageBox offers for our use. Below is an example of us utilizing some of the buttons.
Using the setStandardButtons() function, we can pass whichever button-type we want. (See the list of complete button types below)
def show_popup():
msg = QMessageBox(win)
msg.setWindowTitle("Message Box")
msg.setText("This is some random text")
msg.setIcon(QMessageBox.Question)
msg.setStandardButtons(QMessageBox.Cancel|QMessageBox.Ok
|QMessageBox.Retry)
msg.setInformativeText("This is some extra informative text")
x = msg.exec_()

You may have noticed this already, but the order the buttons has no impact on how they appear on the message box.
Default Button
Look at the above image again. You’l have noticed that there is a blue outline around the “OK” button. This is the symbol of the default button.
Using the setDefaultButton() function we can change the default button. Adding the following line to our code will cause the blue highlight to be around the “Cancel” button.
msg.setDefaultButton(QMessageBox.Cancel)

Here’s a complete list of different buttons types you can use with Messages.
- QMessageBox.Ok
- QMessageBox.No
- QMessageBox.Yes
- QMessageBox.Cancel
- QMessageBox.Close
- QMessageBox.Abort
- QMessageBox.open
- QMessageBox.Retry
- QMessageBox.Ignore
- QMessageBox.Save
- QMessageBox.Retry
- QMessageBox.Apply
- QMessageBox.Help
- QMessageBox.Reset
- QMessageBox.SaveAll
- QMessageBox.YesToAll
- QMessageBox.NoToAll
Detailed and Informative Text
By default you only have one area in the QMessageBox where you display Text. However, there are two more additional areas that we can unlock to add more text.
The first is an additional text section on the messagebox window itself. It’s like an additional line of text you can add called informative text. You only need to call the setInformativeText() function to add this new area of text.
The second is displayed on an area that expands from the QMessageBox. This is called “Detailed Text”. Setting up this section will automatically create a button that is used to show this area. You only need the setDetailedText() function to create this area.
def show_popup():
msg = QMessageBox(win)
msg.setWindowTitle("Message Box")
msg.setText("This is some random text")
msg.setIcon(QMessageBox.Question)
msg.setStandardButtons(QMessageBox.Cancel|QMessageBox.Ok)
msg.setDefaultButton(QMessageBox.Ok)
msg.setDetailedText("Extra details.....")
msg.setInformativeText("This is some extra informative text")
x = msg.exec_()
app = QApplication(sys.argv)
win = QMainWindow()
win.setGeometry(400,400,300,300)
win.setWindowTitle("CodersLegacy")
button = QtWidgets.QPushButton(win)
button.setText("A Button")
button.clicked.connect(show_popup)
button.move(100,100)
win.show()
sys.exit(app.exec_())
In case it didn’t make sense before, look the code and compare to how the output below has changed.

Clicking the Hide/Show Details button will hide/show the extra area below the messagebox respectively.
Retrieving QMessageBox Values
We’ve discussed alot of different customizations and features above, but we haven’t actually linked any of these different features and buttons to our code.
For example, if we have 3 different buttons on our messagebox, how will we know which one was pressed? This is what we’ll be exploring in this section. The code for this is shown below. Make sure to read it before moving forward.
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
import sys
def show_popup():
msg = QMessageBox()
msg.setWindowTitle("Message Box")
msg.setText("This is some random text")
msg.setIcon(QMessageBox.Question)
msg.setStandardButtons(QMessageBox.Cancel|QMessageBox.Ok)
msg.buttonClicked.connect(popup)
x = msg.exec_()
def popup(i):
print(i.text())
app = QApplication(sys.argv)
win = QMainWindow()
win.setGeometry(400,400,300,300)
win.setWindowTitle("CodersLegacy")
button = QtWidgets.QPushButton(win)
button.setText("A Button")
button.clicked.connect(show_popup)
button.move(100,100)
win.show()
sys.exit(app.exec_())
Using the buttonClicked.connect() method, we can cause a function to be triggered whenever a button on the message box is clicked. In this case, we’ve linked our messagebox to a function called popup. Notice that popup() takes a parameter i.
When the messagebox button is clicked it automatically passes the button that was clicked to the function declared in buttonClicked.connect(). Calling the text() function on this button will return it’s text value.
Head over to our main PyQt5 section to learn more about the other great widgets!
This marks the end of the PyQt5 QMessageBox article. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article content can be asked in the comments section below.