Меню

Pyqt диалоговое окно ошибка

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

'''
О диалоге
 Ошибка диалогового окна
 Предупреждение Диалог
 Вопрос: диалог
 Сообщение Диалог
'''
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class QMessageboxDemo(QWidget):
    def __init__(self):
        super(QMessageboxDemo,self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("Cmessagebox Case")

        self.resize(300,400)

        layout = QVBoxLayout()
        self.button1 = QPushButton(«Дисплей о диалоге»)
        self.button1.clicked.connect(self.showdialog)
        # Диалог отображения сообщения
        self.button2 = QPushButton(«Дисплейное сообщение» Диалог ')
        self.button2.clicked.connect(self.showdialog)
        #предостережение
        self.button3 = QPushButton(«Диалог предупреждения отображения»)
        self.button3.clicked.connect(self.showdialog)
        #          
        self.button4 = QPushButton(«Дисплей ошибки Диалог»)
        self.button4.clicked.connect(self.showdialog)

        # Диалог вопроса
        self.button5 = QPushButton(«Дисплей вопрос диалог»)
        self.button5.clicked.connect(self.showdialog)

        layout.addWidget(self.button1)
        layout.addWidget(self.button2)
        layout.addWidget(self.button3)
        layout.addWidget(self.button4)
        layout.addWidget(self.button5)
        self.setLayout(layout)
    def showdialog(self):
        text = self.sender().text()

        if text == «Дисплей о диалоге»:
            # Qmessagebox.about (self, 'title', 'content')
            QMessageBox.about(self,'на',«Это вопрос о диалоге»)
        elif text == «Дисплейное сообщение» Диалог ':
            reply = QMessageBox.information(self,'Новости',«Это сообщение сообщение».,
            QMessageBox.Yes | QMessageBox.No,QMessageBox.Yes)
            print(reply)
        elif text == «Диалог предупреждения отображения»:
            QMessageBox.warning(self,'предостережение',«Это диалог предупреждения», QMessageBox.Yes | QMessageBox.No,QMessageBox.Yes)
        elif text == «Дисплей ошибки Диалог»:
            QMessageBox.critical(self, 'ошибка', «Это диалоговое окно ошибки», QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
        elif text == «Дисплей вопрос диалог»:
            QMessageBox.critical(self, 'Подсказка', «Это оперативное диалоговое окно», QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)


if __name__ == '__main__':
    app =QApplication(sys.argv)
    main = QMessageboxDemo()
    main.show()
    app.exit(app.exec_())

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

Поделиться

Ещё вопросы

  • 1FileNotFoundError при копировании файлов в каталог
  • 1Вызывает ли управляемый активностью курсор Requery () в другом потоке?
  • 1Клавиатура не вводит ничего Java
  • 0JQuery, как перейти к HREF DIV автоматически?
  • 1Elasticsearch вызывает java.lang.LinkageError с помощью javax / servlet / FilterConfig на Tomcat 7
  • 1Код читает целое число как число с плавающей запятой
  • 1найти дату выхода приложения в Android
  • 0OnsenUI: объединить панель вкладок, слайд-меню и диалоги
  • 0WT сохранить файл диалоговое окно?
  • 1Как выбрать строки в CSV-файле на основе списка
  • 0angularjs ngdialog не работает
  • 1Как отсортировать 2-х мерный массив по 4-му значению?
  • 0Преимущества подхода jQuery для делегированных событий для Grid
  • 0JQuery: вызвать внутреннюю ссылку в прокручиваемом div
  • 0изменить отображаемое письмо отправителя по phpmailer
  • 1SEVERE: SAAJ0537: недопустимый тип содержимого. Может быть сообщение об ошибке вместо сообщения SOAP
  • 1Как мы можем подключить пользователя к чату Gmail?
  • 1Пакетная вставка из элемента управления Repeater с помощью флажка
  • 0Изменить якорный текст и значок с помощью jquery начальной загрузки
  • 0Создание нескольких флажков из вложенного объекта json AngularJS
  • 1открыть исходный терминал из питона
  • 0Объединить стол MySQL
  • 0jQuery и PHP получают определенную таблицу из MYSQL для определенного переданного идентификатора через jquery
  • 0Изучение Ember.js — Как бы я это сделал?
  • 1Исключение файла не найдено в приложении Windows Phone
  • 1Как обрабатывать нулевые значения базы данных в приложении Hibernate?
  • 0Должны ли модели MVC быть статичными?
  • 0Эмулятор пульсаций, выдающий 404 для локального файла
  • 0Неверное значение из DDX_CBIndex ()
  • 0AngularJS — Как изменить маршрут, только если что-то верно? [Дубликат]
  • 1очистить очередь rabbitmq с помощью весеннего шаблона amqp?
  • 1ViewModel для макета
  • 0Restangular — Увеличение и обновление значения
  • 1Flower — Инструмент мониторинга асинхронных задач Celery — Веб-API Flask / Docker
  • 0Директива триггера по щелчку
  • 1Автозаполнение формы входа в Facebook
  • 1Почему я не могу заставить эти расширения работать?
  • 0Как читать данные из таблицы в MySQL из Java
  • 0Ошибка времени выполнения с матрицей, реализованной 2d Vector
  • 1Значение шифрования Java не соответствует значению шифрования javascript
  • 0стилус: добавьте стиль к идентификатору, который генерируется в JavaScript
  • 0Изменить ширину элемента внутри директивы AngularJS
  • 0Поиск записей условий с помощью модели hasMany Cakephp3
  • 1Hibernate: ограничить количество строк в таблице
  • 0Как оформить определенный тд в каждой третьей строке таблицы?
  • 1Я не знаю, почему я получаю исключение за пределами границ?
  • 0Выберите HTML изменить другой выберите HTML из функции обмена
  • 1EventQueue.invokeLater vs Thread.start
  • 0URL вставлен дважды
  • 1Как поймать клик пользователя на экране андроида любого приложения?

В обычном Python (3.x) мы всегда используем showerror () из модуля tkinter для отображения сообщения об ошибке, но что мне делать в PyQt5, чтобы отображать точно такой же тип сообщения?

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_()


14

mfitzp
24 Окт 2016 в 20:43

Все вышеперечисленные опции не работают для меня, используя Komodo Edit 11.0. Только что вернул «1» или, если не реализовано, «-1073741819».

Для меня было полезно: решение Vanloc.

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


5

ZF007
13 Ноя 2017 в 23:13

Следующее должно работать:

msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setText("Error")
msg.setInformativeText(e)
msg.setWindowTitle("Error")

Это не тот же тип сообщения (разные GUI), но довольно близко. e — выражение для ошибки в python3

Надеюсь, что помог, Нарусан


3

ekhumoro
25 Окт 2016 в 17:35

Чтобы показать окно сообщения, вы можете вызвать это определение:

from PyQt5.QtWidgets import QMessageBox, QWidget

MainClass(QWidget):
    def __init__(self):
        super().__init__()

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


4

Karam Qusai
17 Апр 2019 в 12:45

Не забудьте вызвать .exec () _ для отображения ошибки:

msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setText("Error")
msg.setInformativeText('More information')
msg.setWindowTitle("Error")
msg.exec_()


11

NShiell
8 Янв 2019 в 15:02

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Pyinstaller ошибка после компиляции
  • Pygame error font not initialized ошибка