Pyqt сообщение об ошибке

Assuming you are in a QWidget from which you want to display an error message, you can simply use QMessageBox.critical(self, "Title", "Message"), replace self by another (main widget for example) if you are not is a QWidget class.


Edit: even if you are not in a QWidget (or don’t want to inherit from it), you can just use None as parent with for instance QMessageBox.critical(None, "Title", "Message").


Edit, here is an example of how to use it:

# -*-coding:utf-8 -*

from PyQt5.QtWidgets import QApplication, QMessageBox
import sys

# In this example, success is False by default, and
#  - If you press Cancel, it will ends with False,
#  - If you press Retry until i = 3, it will end with True


expectedVal = 3


def MyFunction(val: int) -> bool:
    return val == expectedVal


app = QApplication(sys.argv)
i = 1
success = MyFunction(i)
while not success:
    # Popup with several buttons, manage below depending on choice
    choice = QMessageBox.critical(None,
                                  "Error",
                                  "i ({}) is not expected val ({})".format(i, expectedVal),
                                  QMessageBox.Retry | QMessageBox.Cancel)
    if choice == QMessageBox.Retry:
        i += 1
        print("Retry with i = {}".format(i))
        success = MyFunction(i)
    else:
        print("Cancel")
        break

if success:
    # Standard popup with only OK button
    QMessageBox.information(None, "Result", "Success is {}".format(success))
else:
    # Standard popup with only OK button
    QMessageBox.critical(None, "Result", "Success is {}".format(success))

Александр Рублев

@Meller008

Если я правильно понял вопрос, то например

if error:
    QMessageBox.critical(self, "Ошибка ", "Выделите элемент который хотите изменить", QMessageBox.Ok)

Ответ написан

более трёх лет назад


Комментировать


Комментировать

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

Last Updated :
23 Sep, 2021

Like Article

Save Article

Assuming you are in a QWidget from which you want to display an error message, you can simply use QMessageBox.critical(self, "Title", "Message"), replace self by another (main widget for example) if you are not is a QWidget class.


Edit: even if you are not in a QWidget (or don’t want to inherit from it), you can just use None as parent with for instance QMessageBox.critical(None, "Title", "Message").


Edit, here is an example of how to use it:

# -*-coding:utf-8 -*

from PyQt5.QtWidgets import QApplication, QMessageBox
import sys

# In this example, success is False by default, and
#  - If you press Cancel, it will ends with False,
#  - If you press Retry until i = 3, it will end with True


expectedVal = 3


def MyFunction(val: int) -> bool:
    return val == expectedVal


app = QApplication(sys.argv)
i = 1
success = MyFunction(i)
while not success:
    # Popup with several buttons, manage below depending on choice
    choice = QMessageBox.critical(None,
                                  "Error",
                                  "i ({}) is not expected val ({})".format(i, expectedVal),
                                  QMessageBox.Retry | QMessageBox.Cancel)
    if choice == QMessageBox.Retry:
        i += 1
        print("Retry with i = {}".format(i))
        success = MyFunction(i)
    else:
        print("Cancel")
        break

if success:
    # Standard popup with only OK button
    QMessageBox.information(None, "Result", "Success is {}".format(success))
else:
    # Standard popup with only OK button
    QMessageBox.critical(None, "Result", "Success is {}".format(success))

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

Уведомления

  • Начало
  • » Python для новичков
  • » Вывод ошибки от PyQt5 в консоль

#1 Авг. 1, 2017 09:41:14

Вывод ошибки от PyQt5 в консоль

При использовании PyQt5, например при нажатии кнопки к которой привязана функция, если что-либо в ней (функции) идет не так — программа “падает” и ничего не выдается об ошибке в консоль IDE (в моем случае PyCharm), возможно кто знает, как это исправить?

upd (решение):

https://stackoverflow.com/questions/34363552/python-process-finished-with-exit-code-1-when-using-pycharm-and-pyqt5

 # Back up the reference to the exceptionhook
sys._excepthook = sys.excepthook
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)
# Set the exception hook to our wrapping function
sys.excepthook = my_exception_hook
 try:
    sys.exit(app.exec_())
except:
    print("Exiting")

Отредактировано gmaksim (Авг. 1, 2017 12:37:16)

Офлайн

  • Пожаловаться

#2 Авг. 1, 2017 10:24:29

Вывод ошибки от PyQt5 в консоль

Трудно представить, как можно неправильно запустить программу в пайшарме, но кажется, вам это удалось

Офлайн

  • Пожаловаться

#3 Авг. 1, 2017 10:25:54

Вывод ошибки от PyQt5 в консоль

Хотя, может быть просто не туда глядите

Офлайн

  • Пожаловаться

#4 Авг. 1, 2017 10:39:43

Вывод ошибки от PyQt5 в консоль

Да как бы не так.
print в функциях работают и выдают информацию (“навесил” для теста). Пример работы консоли и “падения” программы в приложении.

По коду — вызывается класс, в классе идут методы один за другим, в них вызывается GUI другими методами с разными параметрами. Есть метод для сохранения данных в БД, вот там и падает, и это точно какая-то особенность использования в качестве GUI — PyQt5 — так как при использовании tkinter — условно при нажатии кнопки запуска функции сохранения в БД в консоль выводило ошибку, почему она не срабатывала, тут же просто “падает”.

Отредактировано gmaksim (Авг. 1, 2017 10:43:56)

Прикреплённый файлы:
attachment 2.PNG (18,8 KБ)

Офлайн

  • Пожаловаться

#5 Авг. 1, 2017 10:47:32

Вывод ошибки от PyQt5 в консоль

gmaksim
При использовании PyQt5, например при нажатии кнопки к которой привязана функция, если что-либо в ней (функции) идет не так — программа “падает” и ничего не выдается об ошибке в консоль IDE (в моем случае PyCharm), возможно кто знает, как это исправить?
Онлайн

есть такое и именно в PyQt5. это особенность сборки походу, в С++ такое бывает при сегфолте или нуль-пойнтере. можно из терминала запускать типа python -v my_script

Офлайн

  • Пожаловаться

#6 Авг. 1, 2017 10:57:29

Вывод ошибки от PyQt5 в консоль

gmaksim
Ну блин, вы так вопрос задаете “ничего не выдается об ошибке в консоль IDE” как будто у вас нет сообщения об ошибке именно в терминале пайшарма, а другом терминале — все нормально.
PyQt — это набор питоньих обвязок над бинарниками Qt, если что-то “падает” при выполнении этого бинарного кода мы никогда не получим питоньего трейсбэка. Просто, примите это как должное.

Офлайн

  • Пожаловаться

#7 Авг. 1, 2017 11:17:21

Вывод ошибки от PyQt5 в консоль

vic57
есть такое и именно в PyQt5. это особенность сборки походу, в С++ такое бывает при сегфолте или нуль-пойнтере. можно из терминала запускать типа python -v my_script

Получилось, только теперь падает на строчке:

conn = sqlite3.connect(‘DATA//db.sqlite’)
sqlite3.OperationalError: unable to open database file

Наверно надо поменять на абсолютный путь?

FishHook
PyQt — это набор питоньих обвязок над бинарниками Qt, если что-то “падает” при выполнении этого бинарного кода мы никогда не получим питоньего трейсбэка. Просто, примите это как должное.

Как-то так и думал, но надеялся, что может есть пути обхода.
python -v my_script похоже на то.

Отредактировано gmaksim (Авг. 1, 2017 11:17:55)

Офлайн

  • Пожаловаться

#8 Авг. 1, 2017 11:20:42

Вывод ошибки от PyQt5 в консоль

gmaksim
sqlite3.OperationalError: unable to open database file

это уже не Qt ошибка

Офлайн

  • Пожаловаться

#9 Авг. 1, 2017 11:36:42

Вывод ошибки от PyQt5 в консоль

vic57
это уже не Qt ошибка

Угу, я и не имел ввиду, что это Qt ошибка, разобрался, действительно все выводит. Еще раз спасибо.

FishHook
Однако ‘python -v my_script’ (из терминала) все отлавливает (перед “падением”).

Отредактировано gmaksim (Авг. 1, 2017 11:37:10)

Офлайн

  • Пожаловаться

#10 Авг. 1, 2017 11:41:23

Вывод ошибки от PyQt5 в консоль

gmaksim
действительно все отлавливает

Что “всё”? Вы же понимаете, что невозможно показать построчный вывод ошибки в скомпилированной сишной библиотеке. Ваша ошибка возникает явно в питоньем коде, поэтому она и отлавливается.

Офлайн

  • Пожаловаться
  • Начало
  • » Python для новичков
  • » Вывод ошибки от PyQt5 в консоль

В обычном 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

  • Python ошибка takes no arguments
  • Pyqt диалоговое окно ошибка
  • Python действие при любой ошибке
  • Python ошибка math domain error
  • Pyinstaller ошибка при компиляции