0

I'm new in python and what I'm trying to do is reading an excel file, but I'm stuck due to that I don't want to read the file as soon as I open it, I wan't to press a button to read the file and do what I have to.

When I press "Calcular", I wan't to read the file, but right now I'm trying to print the path in a label with that button, to make sure my button is getting the path in the Entry.

Right now it prints the path in the label without pressing the button "Calcular", how can I pass the entry value as an argument? "lbl2" is where I wan't to print the Entry value (txtfld) using the button "Calcular".

 from tkinter import *
from tkinter.filedialog import askopenfilename

def import_csv_data():
    global v
    csv_file_path = askopenfilename()
    File = open(csv_file_path)
    v.set(csv_file_path)

def calcular(ruta):
    global v2
    v2.set(ruta)

window=Tk()
window.title('Calcular Media') #Titulo
v = StringVar()
v2 = StringVar()

v2 = v
lbl = Label(window, text="Ruta", width=10, height=1).grid(row=0, column=0) 
txtfld = Entry(window, textvariable=v).grid(row=0, column=1)
btn = Button(window, text="Calcular", command=calcular(v.get())).grid(row=0, column=2)
btn2 = Button(window, text="Buscar archivo", command=import_csv_data).grid(row=1, column=0)

lbl2 = Label(window, textvariable=v2).grid(row=5, column=0)

window.geometry("400x300")
window.mainloop()

1 Answers1

0

You need to pass in a callable, without calling it yourself. It looks like a job for a lambda:

btn = Button(window, text="Calcular", command=lambda: calcular(v.get())).grid(row=0, column=2)
quamrana
  • 37,849
  • 12
  • 53
  • 71
  • Hi, thank you for answering, I tried this but it still prints the Entry value in the label (lbl2) as soon as I select the file. – Luis Villegas Jun 19 '21 at 20:00
  • Does the line `v2 = v` conflate the two `StringVar` instances? – quamrana Jun 19 '21 at 20:03
  • oh, thank you for the observation, I fotgot about that line, I added it just to try some stuff, now I deleted it and it works with the code above with lambda, thank you so much – Luis Villegas Jun 19 '21 at 20:05
  • @quamrana Isn't it better to close the question as a duplicate of [this](https://stackoverflow.com/a/5767256/11106801), instead of writing an answer? – TheLizzard Jun 19 '21 at 20:06
  • Ok, if only I had known there was already a duplicate. – quamrana Jun 19 '21 at 20:09