如何从python(pandas和tkinter)中的现有列表中创建下拉列表

2024-04-19 09:51:27 发布

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

我希望用户提交他们的csv excel文件,并从下拉菜单中选择要分析的列

import pandas as pd 
import os 
import sys
from tkinter import *

root = Tk()
root.title('Eng3')

filepath = input('Enter filepath: ')    
assert os.path.exists(filepath), "I did not find the file at, " + str(filepath)
f = open(filepath, 'r+')
print("Hooray we found your file!")   
f.close()   

file = pd.read_csv(filepath, encoding='latin1', delimiter=',')   
column_list = file.columns.tolist()
print(column_list)

因此,我将excel文件中的列名称放入一个列表中。如何在此列表(列列表)中创建下拉菜单以显示所有列名?当我尝试时:

tkvar = StringVar(column_list)
menu = OptionMenu(root, tvkar, column_list)

我得到这个错误:

AttributeError: 'list' object has no attribute '_root'

1条回答
网友
1楼 · 发布于 2024-04-19 09:51:27

我环顾四周,发现了这篇文章。非常有用

file = pd.read_csv(filepath, encoding='latin1', delimiter=',')  
column_list = file.columns.tolist() #convert pandas dataframe to simple python list    

OPTIONS = column_list  #this is what solved my problem

master = Tk()
master.title('Eng3')
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value


w = OptionMenu(master, variable, *OPTIONS)
w.pack()

def ok():
  print ("value is:" + variable.get())

button = Button(master, text="OK", command=ok)
button.pack()

相关问题 更多 >