【问题标题】:Invalid file path for button box按钮框的文件路径无效
【发布时间】:2019-11-03 13:14:26
【问题描述】:

我正在创建一个带有两个按钮的窗口 - 一个用于导入 excel 文件,另一个用于在选择 excel 工作表后关闭窗口。我可以选择 excel 文件,但是当我单击确定时,我收到一个错误,指出我的文件路径无效。

使用 python 2.7

import Tkinter, tkFileDialog
import pandas as pd

root= Tkinter.Tk()

canvas = Tkinter.Canvas(root, width = 300, height = 300, bg = 'PowderBlue')
canvas.pack()

def getExcel ():
    global df

    import_file_path = tkFileDialog.askopenfilenames(title = 'Select file(s)',filetypes = (('Excel','*.xlsx'),('Comma Delimited','*.csv'),('xls', '*.xls')))
    df = pd.read_excel (import_file_path)
    print (df)

okay = Tkinter.Button(text='Okay', command=root.destroy, bg='blue', fg='white', font=('Arial', 10, 'bold'))
canvas.create_window(150, 200, window=okay)

browse_excel = Tkinter.Button(text='Import Excel File(s)', command = getExcel, bg='gray23', fg='white', font=('helvetica', 12, 'bold'))
canvas.create_window(150, 150, window = browse_excel)


root.mainloop()

我得到的错误

 raise ValueError(msg.format(_type=type(filepath_or_buffer)))
ValueError: Invalid file path or buffer object type: <type 'tuple'>

【问题讨论】:

    标签: python pandas tkinter mainloop


    【解决方案1】:

    tkFileDialog.askopenfilenames(...) 返回一个一个或多个文件名的元组。你不能把这个元组直接传递给read_excel();您必须遍历元组的内容并为每个文件名调用一次该函数:

    filenames = tkFileDialog.askopenfilenames(...)
    for filename in filenames:
        df = pd.read_excel(filename)
        print(df)
    

    或者您可以调用askopenfilename()(注意末尾没有s)获取单个文件名。

    【讨论】:

    • 我要导入多个文件。
    • 好的,因此您需要遍历元组的内容并在每个单独的文件名上调用 read_excel()
    • 我该如何写出来?
    • 查看我的更新答案。我的示例代码为每个 excel 文件重复使用相同的数据框;如果您想保留单独的数据框,则必须进行调整。
    猜你喜欢
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    • 2015-04-09
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多