python: 使用选择框获取除getString()外的数据

0 投票
1 回答
961 浏览
提问于 2025-04-16 18:50

我定义了一个对象,这个对象有几个属性。

class thing(object):
    def __init__(self, type, name, attrA, attrB, attrC):
        self.type = type
        self.name = name
        self.attrA = attrA
        self.attrB = attrB
        self.attrC = attrC

假设我有一个东西的列表。

self.things=[thing('car','fred',1,2,3),
             thing('car','george',a,b,c),
             thing('truck','bob',6,7,8),
             thing('truck','tom',x,y,z)
            ]

然后我用这个列表中的一些项目来填充一个选择框。

for each in self.things:
    if each.type == 'car':
       self.choiceCar.Append(item=each.name)

当用户从下拉菜单中选择“Bob”时,我会为这个操作设置一个事件。

def EvtChoice(self,event):
    self.Name = event.GetString()

这个事件可以捕捉到用户选择的名字,但我该如何获取其他属性呢?我现在的做法是:

     for each in self.items:
        if self.Name == each.name
          #Get other things here

我在想,如果我的列表变得很大,那么遍历整个列表会变得非常低效,而且其实没必要,因为用户已经选择了我想要的特定项目。我认为我应该能够获取到所选项目的索引,但我不太确定该怎么做,或者这是否是正确的方法。

1 个回答

2

把数据或对象和 wx.Choice 或 wx.ComboBox 关联起来其实很简单。你可以在这里看到一个使用 wx.ComboBox 的例子:

http://www.blog.pythonlibrary.org/2010/12/16/wxpython-storing-object-in-combobox-or-listbox-widgets/

基本的思路是先给控件的构造函数传一个空列表,然后遍历这些对象,把它们一个个添加到控件里。就像这样:

for obj in self.things:
    self.choiceCar.Append(obj.name, obj)

然后在这个控件的事件处理函数里,你可以通过下面的方式把对象取回来:

obj = self.choiceCar.GetClientData(self.choiceCar.GetSelection())

撰写回答