这条简单的线:
wx.MessageBox('Foo', 'Bar', wx.OK | wx.ICON_ERROR)
给我一个带有错误图标和 Windows 错误噪音的消息框(这与噪音不同wx.Bell()
)。我想为未捕获的异常创建一个自定义错误对话框,其中回溯在文本控件等中可用,并且我想包括 Windows 错误图标和噪音。我知道两者在 Windows 版本之间有所不同,甚至可以自定义错误噪音。
在 wxPython 中使用这些本机 Windows 资源是否有任何直接的方法?奖金问题;如果答案是否定的,那么做我想做的最直接的方法是什么?
接受答案后的结果:
在匿名懦夫的出色回答之后,我只是想炫耀一下结果,因为它们远远超出了我的预期。这是现在在未处理的异常上弹出的错误对话框(在 Windows 8 上):
它还包含现代 Windows“UNNK!” 错误声音。这是对话框背后的代码。我将它放在一个单独的模块中,该模块sys.excepthook
在导入时会覆盖:
"""This module, when imported, overrides the default unhandled exception hook
with one that displays a fancy wxPython error dialog."""
import sys
import textwrap
import traceback
import winsound
import wx
def custom_excepthook(exception_type, value, tb):
dialog = ExceptionDialog(exception_type, value, tb)
dialog.ShowModal()
# Override sys.excepthook
sys.excepthook = custom_excepthook
class ExceptionDialog(wx.Dialog):
"""This class displays an error dialog with details information about the
input exception, including a traceback."""
def __init__(self, exception_type, exception, tb):
wx.Dialog.__init__(self, None, -1, title="Unhandled error",
style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
self.SetSize((640, 480))
self.SetMinSize((420, 200))
self.exception = (exception_type, exception, tb)
self.initialize_ui()
winsound.MessageBeep(winsound.MB_ICONHAND)
def initialize_ui(self):
extype, exception, tb = self.exception
panel = wx.Panel(self, -1)
# Create the top row, containing the error icon and text message.
top_row_sizer = wx.BoxSizer(wx.HORIZONTAL)
error_bitmap = wx.ArtProvider.GetBitmap(
wx.ART_ERROR, wx.ART_MESSAGE_BOX
)
error_bitmap_ctrl = wx.StaticBitmap(panel, -1)
error_bitmap_ctrl.SetBitmap(error_bitmap)
message_text = textwrap.dedent("""\
I'm afraid there has been an unhandled error. Please send the
contents of the text control below to the application's developer.\
""")
message_label = wx.StaticText(panel, -1, message_text)
top_row_sizer.Add(error_bitmap_ctrl, flag=wx.ALL, border=10)
top_row_sizer.Add(message_label, flag=wx.ALIGN_CENTER_VERTICAL)
# Create the text control with the error information.
exception_info_text = textwrap.dedent("""\
Exception type: {}
Exception: {}
Traceback:
{}\
""")
exception_info_text = exception_info_text.format(
extype, exception, ''.join(traceback.format_tb(tb))
)
text_ctrl = wx.TextCtrl(panel, -1,
style=wx.TE_MULTILINE | wx.TE_DONTWRAP)
text_ctrl.SetValue(exception_info_text)
# Create the OK button in the bottom row.
ok_button = wx.Button(panel, -1, 'OK')
self.Bind(wx.EVT_BUTTON, self.on_ok, source=ok_button)
ok_button.SetFocus()
ok_button.SetDefault()
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(top_row_sizer)
# sizer.Add(message_label, flag=wx.ALL | wx.EXPAND, border=10)
sizer.Add(text_ctrl, proportion=1, flag=wx.EXPAND)
sizer.Add(ok_button, flag=wx.ALIGN_CENTER | wx.ALL, border=5)
panel.SetSizer(sizer)
def on_ok(self, event):
self.Destroy()
我希望的唯一改进是让静态文本根据对话框的宽度自动流动和换行,但我不会为此费心制作自定义控件类。