Search code examples
imagewxpythontransparency

wxPython - Putting a transparent PNG image on top of another


I need to display a transparent .png image on top of a normal picture. I have tried this aproach, but wxPython says

wxPaintDC can't be created outside wxEVT_PAINT handler

and I can't find a workaround. I binded a wx.EVT_PAINT to some function and tried the code there, with no sucess. Here's my code:

import wx

class Test(wx.Frame):
    def __init__(self, parent):
        super().__init__(parent)

        self.SetTitle('Testing transparency')
        self.baseImage = wx.StaticBitmap(self, wx.ID_ANY)

        self.DrawBaseImage()
        self.DrawOnTop()

    def DrawBaseImage(self):
        bitmap = wx.Bitmap('path', wx.BITMAP_TYPE_ANY)
        image = wx.Bitmap.ConvertToImage(bitmap)
        self.baseImage.SetBitmap(image.ConvertToBitmap())

    def DrawOnTop(self):
        bmp = wx.StaticBitmap(self.baseImage, wx.ID_ANY)

        bitmap = wx.Bitmap('path_of_transparent_image', wx.BITMAP_TYPE_PNG)
        image = wx.Bitmap.ConvertToImage(bitmap)
        bmp.SetBitmap(image.ConvertToBitmap())


app = wx.App()
Test(None).Show()
app.MainLoop()

Thank you!


Solution

  • Found the solution. Just needed to use wx.EVT_PAINT in the right way!

    import wx
    
    class Test(wx.Panel):
        def __init__(self, parent):
            super().__init__(parent)
    
            self.base = wx.Bitmap('base', wx.BITMAP_TYPE_ANY)
            self.png = wx.Bitmap('transparent_image', wx.BITMAP_TYPE_PNG)
    
            self.Bind(wx.EVT_PAINT, self.OnPaint)
    
        def OnPaint(self, e):
            dc = wx.PaintDC(self)
            dc.SetBackground(wx.Brush("WHITE"))
    
            dc.DrawBitmap(self.base, 0, 0, True)
            dc.DrawBitmap(self.png, 0, 0, True)
    
    
    class Frame(wx.Frame):
        def __init__(self, parent):
            super().__init__(parent)
            Test(self).Show()
    
    app = wx.App()
    Frame(None).Show()
    app.MainLoop()