wxPythonのwxImageで画像を表示する
画像を読み込んで表示させる簡単な例です。(file open error == IOErrorの処理を入れないといけない)
利用するクラスはwx.Image。初期化で読み込む画像ファイルパスを指定します。
Imageインスタンスそのままでは表示できなくて、bitmapに変換してから初めて表示できます。
StaticBitmapで要素に画像を張り付けることができるみたいです。
import wx class myFrame(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, title=title) image = wx.Image('test.jpg') self.bitmap = image.ConvertToBitmap() wx.StaticBitmap(self, -1, self.bitmap, (0,0), self.GetClientSize()) self.SetSize(image.GetSize()) app = wx.App(False) frame = myFrame(None, "Image Viewer") frame.Show() app.MainLoop()
デバイスコンテキストを取得してbitmapを描画する方法でも画像を表示(描画)できます。
デバイスコンテキストはwx.PaintDC(window)で得られるのですが、
"Paintイベント"のときにしか取得できないので、onPaintイベントハンドラを作成します。
import wx class myFrame(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, title=title) self.Bind(wx.EVT_PAINT, self.OnPaint) image = wx.Image('test.jpg') self.bitmap = image.ConvertToBitmap() self.SetSize(image.GetSize()) def OnPaint(self, event=None): deviceContext = wx.PaintDC(self) deviceContext.Clear() deviceContext.SetPen(wx.Pen(wx.BLACK, 4)) deviceContext.DrawBitmap(self.bitmap, 0, 0, True) app = wx.App(False) frame = myFrame(None, "Image Viewer") frame.Show() app.MainLoop()