【问题标题】:How to add columns to a tkinter.Listbox?如何将列添加到 tkinter.Listbox?
【发布时间】:2018-01-28 09:08:24
【问题描述】:

我正在尝试将这些 panda 列添加到 Listbox,因此它们的内容如下:

New Zealand NZD
United States USD

等。

我正在使用 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)

【问题讨论】:

  • 使用字符串"end"。此外,一个列表框只能有一个列。
  • 我想让他们像上面那样显示,然后只使用国家代码作为值,所以我必须创建一个 for 循环或创建要放入列表框中的字符串的东西,但是如何只获取国家代码?

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


【解决方案1】:

您可以将 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()

【讨论】:

  • 按回车键打印当前选择的货币代码。 f-string (f'{country} {code}') 仅适用于 Python 3.6+,在其他版本中您可以使用 .format 方法。
猜你喜欢
  • 2013-09-01
  • 2021-10-20
  • 2013-01-28
  • 1970-01-01
  • 1970-01-01
  • 2012-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多