在wxPython项目中,我有一堆动态创建的按钮。这是一个简单的简化示例:
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)
使用OnClick
函数,例如:
def OnClick(self,event):
button = event.GetEventObject()
d = button.GetName()
[k for k in data if k['name']==d][0]['n'] += 1
然后在链接到另一个小部件的函数中,我需要能够根据用户提供的某些名称禁用其中一些按钮。
如何在未被该按钮触发的功能中根据其名称禁用按钮?
答案 0 :(得分:1)
如何使用字典将按钮名称映射到按钮/索引(到数据项)?
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
# ^^^^^^^^^^^^^^^^