Search code examples
pythonpandastkintermainloop

Invalid file path for button box


I am creating a window with two buttons - one to import excel files and another to close the window after excel sheets are selected. I can choose the excel files, but when I click Okay, I get an error that I have an invalid file path.

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

the error I get it

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

Solution

  • tkFileDialog.askopenfilenames(...) returns a tuple of one or more filenames. You can't pass this tuple directly to read_excel(); you'd have to loop over the contents of the tuple and call that function once per filename:

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

    Or you can call askopenfilename() (note there is no s on the end) for a single filename.