How do I set the color of a toggle button in wxpython?

James Mertz picture James Mertz · Jul 28, 2011 · Viewed 9.9k times · Source

I have a collection of button that I've created and need to change the color of the button when it's pressed. Currently it set the default colors (grey = inactive; light blue = active):

enter image description here

but I want to change the color of active to red.

Here's my button class:

class ButtonClass(wx.Panel):
    def __init__(self, parent, name, id):
        wx.Panel.__init__(self, parent)
        self.name = name
        self.taskid = id

        self.button = wx.ToggleButton(self, 1, size=(50, 50))
        self.button.SetLabel('Start')

        self.mainSizer = wx.BoxSizer(wx.HORIZONTAL)
        self.mainSizer.Add(self.button)

        self.Bind(wx.EVT_TOGGLEBUTTON, self.toggledbutton, self.button)

    # Where the buttons change state
    def toggledbutton(self, event):

        # Active State
        if self.button.GetValue() == True:

            self.button.SetLabel('Stop')

        # Inactive State
        if self.button.GetValue() == False:

            self.button.SetLabel('Start')

I've tried using self.button.SetColour , self.button.SetBackgroundColour , self.button.SetForegroundColour all of which were not successful. Is there a way to accomplish this within wxpython?

Answer

Luke Gregor picture Luke Gregor · Nov 1, 2011

It seems to be platform dependant. This worked for me in Ubuntu, but not in Windows.

self.ToggleButtonObj = wx.ToggleButton(self, -1, 'ButtonLabel')
self.ToggleButtonObj.Bind(wx.EVT_TOGGLEBUTTON, self.OnToggleClick)

def OnToggleClick(self,event):
    if self.ToggleButtonObj.GetValue():
         self.ToggleButtonObj.SetBackgroundColour('#color1')
    else:
         self.ToggleButtonObj.SetBackgroundColour('#color2')

Workaround:

    self.Button = wx.Button(self, -1, 'ButtonLabel')
    self.Button.Bind(wx.EVT_BUTTON, self.OnToggleClick)
    self.ButtonValue = False

    def OnToggleClick(self,event):
        if not self.ButtonValue():
             self.Button.SetBackgroundColour('#color1')
             self.ButtonValue = True
        else:
             self.Button.SetBackgroundColour('#color2')
             self.ButtonValue = False