plannapus
plannapus

Reputation: 18749

Disable buttons created dynamically based on their name in wxPython

In a wxPython project, I have a bunch of buttons that are created dynamically. Here's a minimal simplified example:

data = [{'name':'a', 'n':0}, {'name':'b', 'n':0}, {'name':'c', 'n':0}, {'name':'d', 'n':0}...]
button_names = ['a','b','c','d',...]
button_lab = ['A','B','C','D',...]
N = len(button_names)
g = wx.GridSizer(math.ceil(N/4),4,0,0)
for i in range(0, N-1):
    b = wx.Button(self, wx.ID_ANY, name=button_names[i], label=button_lab[i])
    b.Bind(wx.EVT_BUTTON, self.OnClick)
    g.Add(b, 1, wx_ALL, 5)

With a OnClick function such as this:

def OnClick(self,event):
    button = event.GetEventObject()
    d = button.GetName()
    [k for k in data if k['name']==d][0]['n'] += 1

Then in a function linked to another widget I need to be able to disable some of those buttons based on some names provided by the user.
How can I disable a button based on its name in a function which is not triggered by that button?

Upvotes: 1

Views: 171

Answers (1)

falsetru
falsetru

Reputation: 369064

How about using a dictionary to map button name to buttton / index (to data items)?

data = [{'name':'a', 'n':0}, {'name':'b', 'n':0}, {'name':'c', 'n':0}, {'name':'d', 'n':0}...]
button_names = ['a','b','c','d',...]
button_lab = ['A','B','C','D',...]
N = len(button_names)
g = wx.GridSizer(math.ceil(N/4),4,0,0)
name_to_index = {} # <-------
button_map = {}    # <-------
for i in range(0, N-1):
    b = wx.Button(self, wx.ID_ANY, name=button_names[i], label=button_lab[i])
    name_to_index[button_names[i]] = i # <-------
    button_map[button_map[i]] = b      # <-------
    b.Bind(wx.EVT_BUTTON, self.OnClick)
    g.Add(b, 1, wx_ALL, 5)

def OnClick(self,event):
    button = event.GetEventObject()
    d = button.GetName()
    data[name_to_index[d]]['n'] += 1
    #    ^^^^^^^^^^^^^^^^

Upvotes: 1

Related Questions