如何将列添加到tkinter.Listbox?

时间:2017-08-20 01:25:54

标签: python-3.x pandas csv tkinter listbox

我正在尝试将这些熊猫列添加到Listbox,所以他们会这样读:

New Zealand NZD
United States USD

ETC。

我正在使用pandas从.csv获取数据,但是当我尝试使用for循环使用insert将项添加到列表框时我得到了错误

NameError: name 'END' is not definedNameError: name 'end' is not defined

使用此代码:

def printCSV():
    csv_file = ('testCUR.csv')

    df = pd.read_csv(csv_file)

    print (df[['COUNTRY','CODE']])

your_list = (df[['COUNTRY','CODE']])
for item in your_list:

       listbox.insert(end, item)

1 个答案:

答案 0 :(得分:2)

您可以将csv文件转换为字典,使用组合的国家/地区和货币代码作为键,只使用代码作为值,最后将密钥插入Listbox。要获取当前选择的代码,您可以执行以下操作:currencies[listbox.selection_get()]

listbox.selection_get()会返回您用来获取currencies字典中货币代码的密钥。

import csv
import tkinter as tk

root = tk.Tk()

currencies = {}

with open('testCUR.csv') as f:
    next(f, None)  # Skip the header.
    reader = csv.reader(f, delimiter=',')
    for country, code in reader:
        currencies[f'{country} {code}'] = code

listbox = tk.Listbox(root)
for key in currencies:
    listbox.insert('end', key)
listbox.grid(row=0, column=0)
listbox.bind('<Key-Return>', lambda event: print(currencies[listbox.selection_get()]))

tk.mainloop()