1

我想设计一个wxpython ListCtrl。因此,当单击“搜索”按钮时,我会得到这样的列表

    [(7, u'GLUOCOSE', u'C6H1206'), (8, u'SUCROSE', u'C12H22O11')]

我想用上面的输出填充 listctrl。我是 InsertStringItem 方法,它将返回我当前行的索引,其余列由 SetStringItem() 方法填充。但这给了我 TypeError: String or Unicode type required.我该如何做到这一点?

def OnSearch(self, event):        
    placeholder = '?'
    placeholders = ','.join(placeholder for unused in self.molecule_list)
    query = 'SELECT * FROM MOLECULE WHERE MOL_NUMBER IN (%s)' % placeholders
    cursor = self.conn.execute(query, self.molecule_list)
    final = cursor.fetchall()
    print final 
    for j in final: 
        index = self.list.InsertStringItem(sys.maxint, j[0]) 
        self.list.SetStringItem(index, 1, j[1]) 
        self.list.SetStringItem(index, 2, j[2]) 
4

1 回答 1

1

您正在迭代游标,而不是在变量中返回的数据final。换过来迭代使用final

index = 0
for j in final: 
    index = self.list.InsertStringItem(index, str(j[0])) 
    self.list.SetStringItem(index, 1, j[1]) 
    self.list.SetStringItem(index, 2, j[2])
    index +=1 

最简单的方法,是确保ListCtrl有一个style=wx.LC_REPORT然后使用Append

for j in final:
    self.list.Append((j[0],j[1],j[2],j[3]))

其中 j[n] 是您从数据中需要的每个项目,用于ListCtrl. 我希望这是有道理的。

这是显示这两种方法的示例

import wx
class MyForm(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Molecules")
        panel = wx.Panel(self, wx.ID_ANY)
        self.index = 0
        self.list_ctrl = wx.ListCtrl(panel, size=(-1,100),
                         style=wx.LC_REPORT
                         )
        self.list_ctrl.InsertColumn(0, 'Number')
        self.list_ctrl.InsertColumn(1, 'Element')
        self.list_ctrl.InsertColumn(2, 'Make up')

        btn = wx.Button(panel, label="Add data")
        btn.Bind(wx.EVT_BUTTON, self.add_lines)
        btn2 = wx.Button(panel, label="Append data")
        btn2.Bind(wx.EVT_BUTTON, self.app_lines)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.list_ctrl, 0, wx.ALL|wx.EXPAND, 5)
        sizer.Add(btn, 0, wx.ALL|wx.CENTER, 5)
        sizer.Add(btn2, 0, wx.ALL|wx.CENTER, 5)
        panel.SetSizer(sizer)

    def add_lines(self, event):
        data = [[7, 'GLUCOSE', 'C6H1206'],[8,'SUCROSE', 'C12H22O11']]
        index = 0
        for j in data:
            self.list_ctrl.InsertStringItem(index, str(j[0]))
            self.list_ctrl.SetStringItem(index, 1, j[1])
            self.list_ctrl.SetStringItem(index, 2, j[2])
            index += 1
    def app_lines(self, event):
        data = [[7, 'GLUCOSE', 'C6H1206'],[8,'SUCROSE', 'C12H22O11']]
        for j in data:
            self.list_ctrl.Append((j[0],j[1],j[2]))

if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    frame.Show()
    app.MainLoop()
于 2017-06-22T06:17:38.313 回答