【问题标题】:How to make a dropdown list from an existing list in python (pandas and tkinter)如何从 python (pandas 和 tkinter) 中的现有列表中创建下拉列表
【发布时间】:2021-04-22 15:15:11
【问题描述】:

我希望用户提交他们的 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 文件中的列名列成一个列表。如何从此列表(column_list)中创建一个下拉菜单以显示所有列名?当我尝试时:

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

我收到此错误:

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

【问题讨论】:

    标签: python pandas tkinter


    【解决方案1】:

    我环顾四周,发现了这个帖子How can I create a dropdown menu from a List in Tkinter?。很有用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      • 2021-05-18
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多