0

I want to click the button to execute the function for uploading files from the device when I define the button before the function, it doesn't work, also it doesn't work if I define the button variable after the function.

so, how to solve it?

ahwal_app = Tk()

ahwal_app.geometry("800x500")



def upload_file():
    ahwal_app.filename = filedialog.askopenfilename(initialdir='C:/Users/Manso/Desktop/files/Data Analysis/ahwal',
                                                    title='select file',
                                                    filetypes=(('excel files', '*.xlsx'),('all files', '*.*')))


upload_btn = Button(ahwal_app, text='Upload', bg='orange', width=10, height=2, borderwidth=2, command=upload_file()).pack()



ahwal_app.mainloop()
Mem
  • 9
  • 5
  • 1
    Does this answer your question? [Understanding function call for tkinter button command](https://stackoverflow.com/questions/68588165/understanding-function-call-for-tkinter-button-command) or [Why is the command bound to a Button or event executed when declared?](https://stackoverflow.com/questions/5767228/why-is-the-command-bound-to-a-button-or-event-executed-when-declared) – matszwecja May 26 '22 at 09:30

1 Answers1

1

Replace the line with this :

upload_btn = Button(ahwal_app, text='Upload', bg='orange', width=10, height=2, borderwidth=2, command=upload_file)
upload_btn.pack()

Explanation : The command argument takes only the name of the func... If you do the braces then it means you want to invoke the function at the time of packing the button..

We only specify the name of func. we don't call it...

Hope this works

Prakhar Parikh
  • 177
  • 2
  • 13
  • Please don't post answer to questions that are clear duplicates. – matszwecja May 26 '22 at 09:42
  • @matszwecja It is our duty to post answer. At the time of asking question, a person is shown all the related. He must be unclear about something. Therefore he posted. Its my intention to only help the asker, not to spoil the community – Prakhar Parikh May 26 '22 at 09:45
  • It is our duty to *provide* answer. Writing another one that says same thing is pointless. If everyone asking the question did enough research beforehand 20 different possible flags for closing the question wouldn't be necessary. – matszwecja May 26 '22 at 10:43
  • 3
    Thanks, @Prakhar Parikh for your answer, it worked. – Mem May 26 '22 at 10:43
  • 1
    @Mem I am glad that it worked. Please upvote and mark my answer as accepted, so that it would be easy to someone if he/she comes accross the same question – Prakhar Parikh May 26 '22 at 11:27
  • @Mem Thanks for upvoting my answer. But it would be even better if you mark my answer as accepted – Prakhar Parikh May 27 '22 at 10:19