1

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?

3
  • Why don't you use a dictionary? Commented Dec 6, 2013 at 14:42
  • Can you be more specific? Commented Dec 6, 2013 at 14:42
  • I posted an answer. Check it out. Commented Dec 6, 2013 at 14:45

1 Answer 1

1

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
    #    ^^^^^^^^^^^^^^^^
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, so then when i want to disable one of them i go button_map[name].Enable(False)?
@plannapus, Yes, it is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.