Python:需要从列表中删除第一项,然后填充wx.复选框

2024-10-05 10:45:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在编写一个python脚本来分析SNMP数据。我有一个函数,可以读取csv文件,并在复选框中显示标题。我想删除第一个项目,但这样做会使我的复选框不会填充,我无法找出原因。代码如下:

#Generates CheckBoxList with fields from csv (first row)
def onSNMPGen(self,e):
    #reads in first row of csv file; this snmpPaths[0] will likely cause issues with multiple paths -- fix later
    listItems = []
    print "*** Reading in ", self.snmpPaths[0], "....."
    with open(self.snmpPaths[0], 'r') as f: #remember to close csv
        reader = csv.reader(f)
        print "*** Populating Fields ..... "
        for row in reader:
            #Inserts each field into CheckListBox as an item;
            #self.SNMPCheckListBox.InsertItems(row,0)
            listItems.append(row)
            break
        f.close()
    #Need to remove 'Time' (first item) from listItems
    #listItems.pop(0) # this makes it so my CheckListBox does not populate
    #del listItems[0] # this makes it so my CheckListBox does not populate
    for key in listItems:
        self.SNMPCheckListBox.InsertItems(key,0)

Tags: csvinfromselfaswiththisreader
2条回答

多亏了roxan,我在看到我的错误后才得以解决我的问题。我将csv行存储为列表中的一个项目,而不是将行的每一列都作为一个项目。这是我的解决方案:

#Generates CheckBoxList with fields from csv (first row)
def onSNMPGen(self,e):
    #reads in first row of csv file; this snmpPaths[0] will likely cause issues with multiple paths   fix later
    listItems = []
    print "*** Reading in ", self.snmpPaths[0], "....."
    with open(self.snmpPaths[0], 'r') as f: #remember to close csv
        reader = csv.reader(f)
        print "*** Populating Fields ..... "
        for row in reader:
            listItems = row             break
        f.close()
    del listItems[0] #Time is always first item so this removes it
    self.SNMPCheckListBox.InsertItems(listItems,0)
 for row in reader:
            #Inserts each field into CheckListBox as an item;
            #self.SNMPCheckListBox.InsertItems(row,0)
            listItems.append(row)
            break

因为您使用了break,所以您的列表只有一项。因此,当您删除该项时,没有任何内容可以填充您的复选框。你知道吗

如果您100%确定它是第一项,则可以重写循环,如:

 for row in reader[1:]:
            #Inserts each field into CheckListBox as an item;
            #self.SNMPCheckListBox.InsertItems(row,0)
            listItems.append(row)

reader[1:]意味着您只需要在listItems列表中添加第二项。你知道吗

相关问题 更多 >

    热门问题