Search code examples
pythonwxpython

wx.Image constructor shows popup instead of raising an exception


When I run this Python code:

import io, wx

with open("imgs/ad.png", "rb") as fid:
    img_stream = io.BytesIO(fid.read())
try:
    img = wx.Image(img_stream, type=wx.BITMAP_TYPE_PNM)
except:
    pass

it results in a message box saying "Error: This is not a PNM file." instead of raising an exception. Is it possible to have wx raise an exception instead?


Solution

  • As @Rolf-of-Saxony pointed out, the message box is due to wxPython logging. Two basic options for suppressing it are temporary creation of the wx.LogNull() object

    import io
    import wx
    
    with open("imgs/Olympic_flag.svg", "rb") as fid:
        img_stream = io.BytesIO(fid.read())
    noLog = wx.LogNull()
    img = wx.Image(img_stream)
    if img.IsOk():
        pass
    else:
        pass
    del noLog
    

    or calling wx.Log.EnableLogging()

    import io
    import wx
    
    wx.Log.EnableLogging(False)
    img = wx.Image(img_stream)
    if img.IsOk():
        pass
    else:
        pass
    wx.Log.EnableLogging(True)