Search code examples
imagewxpython

wxPython Swap Images


I have been trying to swap 2 pictures in a list. I am adding the list to a GridSizer of 1 row and 2 cols. I have one horizontal BoxSizer where I am adding the GridSizer along with a button upon which, when clicked, the pictures are supposed to be swapped. But I am getting type error string or unicode required. I am using Python 2.7.6 and wxPython 2.8.12.1 (gtk2-unicode) on a Linux Mint 64-bit laptop. Below is the part of my program where the error is occurring. Please help.

Thanks.

def OnOk(self, event):
    x = wx.Image(self.ic[0], wx.BITMAP_TYPE_ANY).Scale(200, 200)
    y = wx.Image(self.ic[1], wx.BITMAP_TYPE_ANY).Scale(200, 200)
    self.ic[0].SetBitmap(wx.StaticBitmap(self, wx.ID_ANY, wx.BitmapFromImage(y)))
    self.ic[1].SetBitmap(wx.StaticBitmap(self, wx.ID_ANY, wx.BitmapFromImage(x)))
    self.Refresh()

Solution

  • I quite do not understand what self.ic is supposed to be (a list of wx.StaticBitmap instances or a list of wx.Bitmap instances). You seem to mix up the both. A StaticBitmap is a wxPython widget, a wx.Bitmap is, well, just a data structure holding bitmap data.

    See a working example below:

    import wx
    
    class bmpframe(wx.Frame):
        def __init__(self, *args, **kwds):
            wx.Frame.__init__(self, *args, **kwds)
    
            pnl = wx.Panel(self, -1)
            # lazy way to make two discernable bitmaps
            # Warning: alpha does not work on every platform/version
            bmp1 = wx.EmptyBitmapRGBA(64, 64, alpha=0)
            bmp2 = wx.EmptyBitmapRGBA(64, 64, alpha=1)
    
            static_bitmap_1 = wx.StaticBitmap(pnl, -1, bitmap=bmp1)
            static_bitmap_2 = wx.StaticBitmap(pnl, -1, bitmap=bmp2)
            self.stbmp1 = static_bitmap_1
            self.stbmp2 = static_bitmap_2
    
            self.btn_swap = wx.Button(pnl, -1, u'Swap…')
    
            szmain = wx.BoxSizer(wx.VERTICAL)
            szmain.Add(static_bitmap_1, 0, wx.EXPAND|wx.ALL, 4)
            szmain.Add(static_bitmap_2, 0, wx.EXPAND|wx.ALL, 4)
            szmain.Add(self.btn_swap, 0, wx.EXPAND|wx.ALL, 4)
    
            pnl.SetSizer(szmain)
            szmain.Fit(self)
    
            self.btn_swap.Bind(wx.EVT_BUTTON, self.on_swap)
    
        def on_swap(self, evt):
            print 'EVT_BUTTON'
            bmp1 = self.stbmp1.GetBitmap()
            bmp2 = self.stbmp2.GetBitmap()
            self.stbmp1.SetBitmap(bmp2)
            self.stbmp2.SetBitmap(bmp1)
            self.Refresh()
    
    if __name__ == '__main__':
        app = wx.App(redirect=False)
        frm = bmpframe(None, -1, 'testbmpswap')
        frm.Show()
    
        app.MainLoop()