How do I create a file chooser using Tkinter?

2.9k views Asked by At

I've been trying to create a file chooser using Tkinter. I want to make it happen when the "select file" button is pressed. The problem, however, is that it automatically opens up instead of opening up the GUI and then creating the file directory window after clicking the button. Am I not creating it properly?

#Creates the Top button/label to select the file
this.l5 = Label(this.root,text = "Boxes File:").grid(row = 0, column = 0)
this.filename = StringVar()
this.e3 = Entry(this.root,textvariable = this.filename)
this.button3 = Button(this.root,text = "Select File",command=filedialog.askopenfilename()).grid(row = 0, column = 7)
mainloop()
2

There are 2 answers

0
TigerhawkT3 On BEST ANSWER
  1. It's not technically required, but you should use the standard self instead of this.
  2. Something like a = Button(root).grid() saves the result of grid() to a, so now a will point to None. Create and assign the widget first, then call the geometry manager (grid(), etc.) in a separate statement.
  3. A widget's command is a function that the widget will call when requested. Let's say we've defined def search_for_foo(): .... Now search_for_foo is a function. search_for_foo() is whatever search_for_foo is programmed to return. This may be a number, a string, or any other object. It can even be a class, type, or a function. However, in this case you'd just use the ordinary command=filedialog.askopenfilename. If you need to pass an argument to the widget's callback function, there are ways to do that.
0
Eshita Shukla On

Change the command attribute of button3. It worked for me.

#Creates the Top button/label to select the file
this.l5 = Label(this.root,text = "Boxes File:").grid(row = 0, column = 0)
this.filename = StringVar()
this.e3 = Entry(this.root,textvariable = this.filename)
# Insert "lambda:" before the function
this.button3 = Button(this.root,text = "Select 
File",command=lambda:filedialog.askopenfilename()).grid(row = 0, column = 7)
mainloop()