Ram*_*elm 4 python message messagebox pyqt5
在普通的Python(3.x)中,我们总是使用来自tkinter模块的showerror()来显示错误消息,但是我应该在PyQt5中做些什么来显示完全相同的消息类型呢?
mfi*_*tzp 11
Qt包含一个特定 于错误消息的对话框类QErrorMessage,您应该使用它来确保对话框符合系统标准.要显示对话框,只需创建一个对话框对象,然后调用.showMessage().例如:
error_dialog = QtWidgets.QErrorMessage()
error_dialog.showMessage('Oh no!')
Run Code Online (Sandbox Code Playgroud)
这是一个最小的工作示例脚本:
import PyQt5
from PyQt5 import QtWidgets
app = QtWidgets.QApplication([])
error_dialog = QtWidgets.QErrorMessage()
error_dialog.showMessage('Oh no!')
app.exec_()
Run Code Online (Sandbox Code Playgroud)
小智 10
不要忘记调用.exec()_来显示错误:
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setText("Error")
msg.setInformativeText('More information')
msg.setWindowTitle("Error")
msg.exec_()
Run Code Online (Sandbox Code Playgroud)
假设您在一个 QWidget 中,想要从中显示错误消息,QMessageBox.critical(self, "Title", "Message")如果您不是 QWidget 类,则可以简单地使用 ,将 self 替换为另一个(例如主窗口小部件)。
编辑:即使您不在 QWidget 中(或者不想从它继承),您也可以仅使用 None 作为实例的父级QMessageBox.critical(None, "Title", "Message")。
编辑,这是如何使用它的示例:
# -*-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))
Run Code Online (Sandbox Code Playgroud)
以上所有选项对我使用 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
Run Code Online (Sandbox Code Playgroud)
要显示消息框,您可以调用此定义:
from PyQt5.QtWidgets import QMessageBox, QWidget
MainClass(QWidget):
def __init__(self):
super().__init__()
def clickMethod(self):
QMessageBox.about(self, "Title", "Message")
Run Code Online (Sandbox Code Playgroud)