How can I store objects other than strings in a wxPython ComboBox?

╄→尐↘猪︶ㄣ 提交于 2020-01-01 19:11:12

问题


I have a list of Vertex objects, each with their own labels and id's. How can I use this list as a model for a wxPython ComboBox such that when a user selects an option, I can immediately retrieve the Vertex id?

It appears that ComboBox only accepts strings as a model. I cannot create a dictionary of label to id pairs since there are duplicate labels.

I noticed a ComboCtrl class which I can subclass to create a specialized combo box, but I feel like there is a easier solution to this.


回答1:


This topic came up on the wxPython IRC channel earlier today, but in regards to the ListBox. Fortunately, both the widgets inherit from wx.ItemContainer, so you can do the following:

for item in ObjList:
    self.myCboBox.append(item.label, item)

Then in the event handler, you'd do something like:

itemObject = self.myCboBox.GetClientData(self.myCboBox.GetSelection())
itemID = itemObject.id

That should work.




回答2:


Most straightforward approach would be storing vertexes in a list and retrieve selected value by index (returned by wx.ComboBox GetSelection()).

Edit: q&d example:

l = [{"value" : value_1, "label" : "label"},
     {"value" : value_2, "label" : "label"}]

def on_select (event):
    i = event.GetSelection()
    print (l[i]["value"])

# ui construction omitted    

Bind (wx.EVT_COMBOBOX, on_slect)


来源:https://stackoverflow.com/questions/4433715/how-can-i-store-objects-other-than-strings-in-a-wxpython-combobox

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