在具有多个togglebuttons的面板中,只有一个按钮会改变颜色 - wxPython

时间:2015-07-16 19:00:44

标签: button wxpython togglebutton

我想在我创建的面板中设置我选择的切换按钮的颜色。问题是,当我想要更改每个按钮的颜色时,我在面板上显示的众多切换按钮中,只有最后一个按钮的颜色发生变化。这是我的代码:

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()

1 个答案:

答案 0 :(得分:0)

你的问题很简单。最后一个按钮总是被更改,因为它是定义的最后一个按钮:

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

每次通过for循环,您都会将self.Button属性重新分配给其他按钮。您要做的是从事件对象中提取按钮并更改其背景颜色。所以改变你的功能看起来像这样:

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

另见: