Reputation: 381
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()
Upvotes: 2
Views: 3206
Reputation: 811
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()
Upvotes: 0
Reputation: 49318
self
instead of this
.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.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.Upvotes: 4