2

I want to send a variable to a function from dynamically created buttons (14 of them)

# creating buttons
    for i in range(0, 14):
        m_pauser.append(wx.Button(panel, 5, "Pause "+str(i)))
        m_pauser[i].Bind(wx.EVT_BUTTON, lambda event: self.dispenser_pause(event, i), m_pauser[i])
        box.Add(m_pauser[i], 0, wx.ALL, 10)


# function called by buttons
    def dispenser_pause(self, event, my_value):
        print my_value

The problem is that all buttons always send 13 (the last value of 'i' in the 'for' loop)

How can I assign a value to a button so it sends it to the function? Is this the right way to make it work?

I just started with Python, so probably there's a lot that I'm missing out

Thanks

1 Answer 1

4

I suppose the issue is that every button gets the same ID, which seems to be 5 in your example. It is a bad habit to hardcode wxwidgets IDs. Use -1 or wx.NewId() instead.

EDIT: It is not the ID (but ID they should be unique, anyway). The reason is that i does point to the last value it had (during the loop, i is always "the same thing" and there are never "distinct i's). Do the following instead:

For the sake of clarity do can do the following:

m_pauser = []
for i in range(0, 14):
    btn = wx.Button(panel, -1, "Pause "+str(i))
    m_pauser.append(btn)
    btn.Bind(wx.EVT_BUTTON, lambda event, temp=i: self.dispenser_pause(event, temp))
    box.Add(btn, 0, wx.ALL, 10)

The reason is explained better in the wxPython wiki than I could do it.

Sign up to request clarification or add additional context in comments.

Comments

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.