Python PyQt5:如何使用PyQt5显示错误消息

Python PyQt5:如何使用PyQt5显示错误消息,python,message,messagebox,pyqt5,Python,Message,Messagebox,Pyqt5,在普通Python(3.x)中,我们总是使用tkinter模块中的showerror()来显示错误消息,但是在PyQt5中我应该做什么来显示完全相同的消息类型呢?以下应该可以工作: msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("Error") msg.setInformativeText(e) msg.setWindowTitle("Error") 它不是完全相同的消息类型(不同的GUI),但非常接近。 e

在普通Python(3.x)中,我们总是使用tkinter模块中的showerror()来显示错误消息,但是在PyQt5中我应该做什么来显示完全相同的消息类型呢?

以下应该可以工作:

msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setText("Error")
msg.setInformativeText(e)
msg.setWindowTitle("Error")
它不是完全相同的消息类型(不同的GUI),但非常接近。
e
是python3中错误的表达式

希望有帮助, Narusan

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

使用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

不要忘记调用
.exec()
以显示错误:

from PyQt5.QtWidgets import QMessageBox

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

要显示消息框,可以调用此def:

from PyQt5.QtWidgets import QMessageBox, QWidget

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

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

假设您在想要显示错误消息的QWidget中,您可以简单地使用
QMessageBox.critical(self,“Title”,“message”)
,如果您不是QWidget类,则用另一个(例如主小部件)替换self。

而不是msg.setIcon(QMessageBox.critical),您应该编写一个数字作为参数。见:@AlanHorman。不,这只是一个输入错误-应该是
QMessageBox.Critical
(即大写字母“C”)。很抱歉,我应该仔细检查拼写检查
.exec\(
提示!工作完美。非常感谢。