Search code examples
buttonwxpythontogglebutton

Only one button in a panel with multiple togglebuttons changes color - wxPython


I want to set the color of a toggle button of my choice in the panel that I have created. The problem is that in the numerous toggle buttons that I have displayed on my panel when I want to change the color of each one only the color of the last button changes. Here's my code:

import wx

class Frame(wx.Frame):

def __init__(self):
    wx.Frame.__init__(self,None)
    self.panel = wx.Panel(self,wx.ID_ANY)

    self.sizer = wx.BoxSizer(wx.VERTICAL)
    self.flags_panel = wx.Panel(self, wx.ID_ANY, style = wx.SUNKEN_BORDER)

    self.sizer.Add(self.flags_panel)
    self.SetSizer(self.sizer,wx.EXPAND | wx.ALL)
    self.flags = Flags(self.flags_panel, [8,12])
    self.flags.Show()

class Flags (wx.Panel):
def __init__(self,panel, num_flags = []):#,rows = 0,columns = 0,radius = 0, hspace = 0, vspace = 0,x_start = 0, y_start = 0
    wx.Panel.__init__(self,panel,-1, size = (350,700))

    num_rows = num_flags[0]
    num_columns = num_flags[1]
    x_pos_start = 10
    y_pos_start = 10

    i = x_pos_start
    j = y_pos_start
    buttons = []
    for i in range (num_columns):
        buttons.append('toggle button')
    self.ButtonValue = False
    for button in buttons:
        index = 0
        while index != 15: 
            self.Button = wx.ToggleButton(self,-1,size = (10,10), pos = (i,j))
            self.Bind(wx.EVT_TOGGLEBUTTON,self.OnFlagCreation, self.Button)
            self.Button.Show()
            i += 15
            index += 1
        j += 15
        i = 10

    self.Show()

def OnFlagCreation(self,event):
    if not self.ButtonValue:
        self.Button.SetBackgroundColour('#fe1919')
        self.ButtonValue = True
    else:
        self.Button.SetBackgroundColour('#14e807')
        self.ButtonValue = False

if __name__ == '__main__':
   app = wx.App(False)
   frame = Frame()
   frame.Show()
   app.MainLoop()

Solution

  • Your problem is quite simple. The last button is always changed because it's the last button defined:

    self.Button = wx.ToggleButton(self,-1,size = (10,10), pos = (i,j))
    

    Each time through the for loop, you reassign the self.Button attribute to a different button. What you want to do is extract the button from your event object and change its background color. So change your function to look like this:

    def OnFlagCreation(self,event):
        btn = event.GetEventObject()
        if not self.ButtonValue:
            btn.SetBackgroundColour('#fe1919')
            self.ButtonValue = True
        else:
            btn.SetBackgroundColour('#14e807')
            self.ButtonValue = False
    

    See also: