Moon
Moon

Reputation: 313

tkinter, get file directory path as a variable for pandas

I want the user to pick a file from file explorer and get its path into a variable, ex:

filepath = "C\User\Random_File\excel_archive.xlsx"

and use that variable to load it into a pandas dataframe

df = pd.read_excel(filepath)

only thing I have now is this:

def fileopen():
 filepath = filedialog.askopenfile()
 label = Label(text=filepath).pack()
 df = pd.read_excel(label)

button_choose_file = Button(window, text='choose file', command = fileopen).pack()

but it doesn't work. How can I solve this?

Upvotes: 1

Views: 1201

Answers (1)

user15801675
user15801675

Reputation:

This might work. Update filedialog.askopenfile() to filedialog.askopenfilename() and pd.read_excel(label) to pd.read_excel(filepath)

from tkinter import *
from tkinter import filedialog
import pandas as pd

window = Tk()

def fileopen():
    filepath = filedialog.askopenfilename(filetypes=(("xlsx", "*.xlsx"), ("all files", "*.*"))) #===assigns the path to filepath
    label = Label(window, text=filepath) #==Adds Label to window 
    label.pack()
    df = pd.read_excel(filepath) #==reads the excel file by fetching it from its path

button_choose_file = Button(window, text='choose file', command=fileopen)
button_choose_file.pack()

window.mainloop()

Upvotes: 3

Related Questions