Goulouh Anwar
Goulouh Anwar

Reputation: 767

How to add columns to a tkinter.Listbox?

I am trying to add these panda columns to a Listbox, so they read like this:

New Zealand NZD
United States USD

ETC.

I am using pandas to get the data from a .csv, but when I try and use a for loop to add the items to the list box using insert I get the error

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

Using this code:

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)

Upvotes: 2

Views: 3836

Answers (1)

skrx
skrx

Reputation: 20488

You could turn the csv file into a dictionary, use the combined country and currency codes as the keys and just the codes as the values, and finally insert the keys into the Listbox. To get the code of the current selection, you can do this: currencies[listbox.selection_get()].

listbox.selection_get() returns the key which you then use to get the currency code in the currencies dict.

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()

Upvotes: 2

Related Questions