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

馋奶兔 提交于 2019-12-11 22:05:40

问题


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

回答1:


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:

  • http://www.blog.pythonlibrary.org/2011/09/20/wxpython-binding-multiple-widgets-to-the-same-handler/


来源:https://stackoverflow.com/questions/31462415/only-one-button-in-a-panel-with-multiple-togglebuttons-changes-color-wxpython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!