Send variables in dynamically created buttons with wxPython

风格不统一 提交于 2019-12-25 09:58:37

问题


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:


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.



来源:https://stackoverflow.com/questions/34998340/send-variables-in-dynamically-created-buttons-with-wxpython

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