I am pretty new to wxpython and trying to create a basic UI.
I want to create a bitmap button with a transparent background. I have read numerous posts on this topic but have not been able to figure out how to make the solutions work for my situation.
My sample code below is for a simplistic layout to illustrate. I have 2 child panels on a parent panel. The topmost panel is supposed to be cyan with a transparent “X” button on it. I have tried to implement the approach of binding EVT_ERASE_BACKGROUND to a null event handler, and this does cause the button to be transparent, but now my panel is not drawn correctly.
import wx
class Panel1(wx.Panel):
def __init__(self, parentPanel, *args, **kwargs):
super().__init__(parentPanel, *args, **kwargs)
self.SetBackgroundColour("#009DD6")
btn = wx.BitmapButton(self, -1, wx.Bitmap('img\\close.png'), (120,120), style=wx.NO_BORDER)
hbox = wx.BoxSizer(wx.HORIZONTAL)
hbox.Add((0,-1), proportion=1)
hbox.Add(btn)
self.SetSizer(hbox)
self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnPaint)
def OnPaint(self, evt):
pass
class Panel2(wx.Panel):
def __init__(self, parent, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.SetBackgroundColour(wx.GREEN)
class MainFrame(wx.Frame):
def __init__(self, *args, **kw):
super().__init__(None, title="test", size=(600,400), *args, **kw)
# Create main panels & titlebar
rootPanel = wx.Panel(self)
panel1 = Panel1(rootPanel, size=(-1,50))
panel2 = Panel2(rootPanel)
# Add main panels to sizer
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(panel1, 0, wx.EXPAND)
sizer.Add(panel2, 1, wx.EXPAND)
rootPanel.SetSizer(sizer)
self.Centre()
self.Show()
def main():
app = wx.App()
mainFrame = MainFrame()
app.MainLoop()
if __name__ == '__main__':
main()
If I comment out the line that binds the EVT_ERASE_BACKGROUND event, I get:
If I include that line, the button is transparent, but the panel is never properly drawn (see image in post below).
How can I put a transparent bitmap button on a panel, but still draw the parent panel correctly?