I'm writing in python a simple excel into folder software using tkinter and pandas. The first step of this program will be the file choice so i wrote
data_path=StringVar()
def getPath():
file = filedialog.askopenfile(mode='r', initialdir='/',
filetypes=[("xlsx files", "*.xlsx")])
if file:
filepath=os.path.abspath(file.name)
data_path.set(filepath)
Label(root, textvariable=data_path).grid(row=1,column=0,sticky='w', padx=100)
labels1_1 = Label (root, text = "Carica un File",
font=('Arial', 12, 'bold')).grid(row=0,column=0,padx=5,sticky='w')
open_button = Button (root, text="Scegli un File",
command=getPath).grid(row=1,column=0, padx=13, pady=5,sticky='w')
but if i set "data_path" as string and than i put into
df = pd.read_excel(data_path)
it doesn't work. So how can i read the dataframe from user's excel file?
Thanks a lot Have a good work
CodePudding user response:
data_path
is an instance of StringVar
, what you need is to get the value of it, so you have to use get()
method to get its value:
df = pd.read_excel(data_path.get())
Furthermore, you don't need askopenfile
, you can just use askopenfilename
which will return the absolute path of the file.
def getPath():
file = filedialog.askopenfilename(initialdir='/',
filetypes=[("xlsx files", "*.xlsx")])
if file:
data_path.set(file)
Label(root, textvariable=data_path).grid(row=1,column=0,sticky='w', padx=100)