本文介绍了使用 wxPython 在动态创建的按钮中发送变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从动态创建的按钮(其中 14 个)向函数发送一个变量

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

问题是所有按钮总是发送 13('for' 循环中 'i' 的最后一个值)

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?

我刚开始使用 Python,所以可能我错过了很多

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

谢谢

推荐答案

我想问题是每个按钮都有相同的 ID,在您的示例中似乎是 5.硬编码 wxwidgets ID 是一个坏习惯.使用 -1wx.NewId() 代替.

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:这不是 ID(但 ID 它们应该是唯一的,无论如何).原因是 i 确实指向它拥有的最后一个值(在循环期间,i 总是相同的东西"并且永远不会有不同的 i's). 改为执行以下操作:

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)

原因在 wxPython wiki 中比我能做到的更好.

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

这篇关于使用 wxPython 在动态创建的按钮中发送变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 13:16
查看更多