2016-03-08 22 views
0

我有一個csv文件,其名稱是第一列,第二列是A或B. 我想分析這個(他們在什麼組),並把名字放到tkinter的相應文本框中,我會怎麼做呢?在csv中分隔組 - 使用tkinter來顯示結果

from tkinter import * 
import csv 

master=Tk() 

file=open(file="Book1.csv") 
f=csv.reader(file) 
people=[] 
for column in f: 
    people.append(column[0:2]) 


classAl=Label(master,text='A',width=10).grid(row=1,column=1) 
classA=Text(master,width=10) 
classA.grid(column=1,row=2) 

classbl=Label(master,text='B',width=10).grid(row=1,column=2) 
classB=Text(master,width=10) 
classB.grid(column=2,row=2) 

print(people) 

grouplist=[x[1] for x in people] 
for names in(grouplist): 
    print(names) 

這是編碼我到目前爲止,我能讀懂他們是在什麼組,但我不知道如何再放入其相應的名稱到正確的位置。 任何幫助,將不勝感激。

回答

1

使用collections.defaultdict,以便將CSV文件的內容通過標籤(見this other stackoverflow question

一個列表框將是您的應用程序更合適的窗口小部件。

import csv 
from collections import defaultdict 
from tkinter import * 

grouped = defaultdict(list) 

# Open the csv file and use the defaultdict to group by label. 
with open('Book1.csv', 'r') as fh: 
    book = csv.reader(fh) 
    for name, label in book: 
     grouped[label].append(name) 

master = Tk() 
A_label = Label(master, text='A', width=10).grid(row=1, column=1) 
A_list = Listbox(master, width=10) 
A_list.grid(column=1, row=2) 
for name in grouped['A']: 
    A_list.insert(END, name) 

B_label = Label(master, text='B', width=10).grid(row=1, column=2) 
B_list = Listbox(master, width=10) 
B_list.grid(column=2, row=2) 
for name in grouped['B']: 
    B_list.insert(END, name) 

master.mainloop() 

最好使用with語句(上下文管理器)打開和讀取csv文件。

我對代碼也應用了一些通用的pep8建議。

+0

謝謝,非常有幫助! –