Search code examples
pythonwxpython

Showing pop up message to show the error message when the code stops running WXPYTHON


I am new in wxpython. Is there any way to show pop up message to show the error message when the code stops running? So the user doesn't need to look at the terminal to see that actually the code stops.

Thanks!


Solution

  • Just to illustrate the comment from @Michael Butscher and the answer from @Dan A.S.

    You can use sys and traceback to catch and display the event in a wx.MessageDialog

    import wx
    import sys, traceback
    
    def my_message(exception_type, exception_value, exception_traceback):
        msg = "Oh no! An error has occurred.\n\n"
        tb= traceback.format_exception(exception_type, exception_value, exception_traceback)
        for i in tb:
            msg += i
        dlg=wx.MessageDialog(None, msg, str(exception_type), wx.OK|wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()
    
    sys.excepthook = my_message
    
    class MyFrame(wx.Frame):
        def __init__(self, parent, id=wx.ID_ANY, title="", size=(360,100)):
            super(MyFrame, self).__init__(parent, id, title, size)
            self.panel = wx.Panel(self)
            self.panel.Bind(wx.EVT_KEY_DOWN, self.OnKey)
            self.Show()
    
        def OnKey(self, event):
            print ("alpha" + 1)
    
    if __name__ == "__main__":
        app = wx.App()
        frame = MyFrame(None,title="Press a key")
        app.MainLoop()
    

    enter image description here