Search code examples
pythonwxpython

wxpython- Color on Bitmap on toolbar not appearing


def createColorTool(self, toolbar, color):
  bmp = self.MakeBitmap(color)
  newId = wx.NewId()
  label=''
  tool = toolbar.AddRadioTool(newId, label,bmp, shortHelp=color)
  self.Bind(wx.EVT_MENU, self.OnColor, tool)
 def MakeBitmap(self, color):
  bmp= wx.EmptyBitmap(16, 15)
  
  dc = wx.MemoryDC()
  dc.SelectObject(bmp)
  
  dc.SetBackground(wx.Brush(color))
  
  dc.SelectObject(wx.NullBitmap)
  return bmp

The color attribute takes in color from a list of colors {'black', 'blue', 'green'} the problem is program is working fine but for bitmap, in the toolbar, only black color is being displayed not any other color as specified in the list for the choose color option. You can see the image here of how the code is working

enter image description here


Solution

  • I get lost with DC manipulation, so here's an alternative.
    This assumes that color is a wx.Colour e.g. wx.Colour(0, 155, 255, alpha=255)

    def MakeBitmap(self, color):
        bmp = wx.Bitmap.FromRGBA(16, 15, color.red, color.green, color.blue, color.alpha)
        return bmp
    

    Creates the Green square below

    enter image description here

    Edit: Your code sets the background brush but doesn't use it.
    So you are returning the bare bones bitmap.

    If you must use a dc try the following:

    def MakeBitmap(self, color):
        bmp = wx.Bitmap(16, 15)
        dc = wx.MemoryDC(bmp)
        dc.SetBackground(wx.Brush(color))
        dc.Clear()
        return bmp
    

    or:

    def MakeBitmap(self, color):
        bmp= wx.Bitmap(16, 15)
        dc = wx.MemoryDC()
        dc.SelectObject(bmp)
        dc.SetBackground(wx.Brush(color))
        dc.Clear()
        return bmp 
    

    Clear(self) Clears the device context using the current background brush.