I would like to make a browse folder button using tkinter and to store the path into a variable. So far i am able to print the path but i am not able to store it in a variable. Can you please advise?
Below i attach the code that i use.
from tkinter import filedialog
from tkinter import *
def browse_button():
filename = filedialog.askdirectory()
print(filename)
return filename
root = Tk()
v = StringVar()
button2 = Button(text="Browse", command=browse_button).grid(row=0, column=3)
mainloop()
In order to create buttons in a Tkinter application, we can use the Button widget. Buttons can be used to process the execution of an event in the runtime of an application. We can create a button by defining the Button(parent, text, **options) constructor.
Use the askopenfilenames() function to display an open file dialog that allows users to select multiple files. Use the askopenfile() or askopenfiles() function to display an open file dialog that allows users to select one or multiple files and receive a file or multiple file objects.
Here is an example of storing the directory path as a global variable and using that to populate a Label.
from tkinter import filedialog
from tkinter import *
def browse_button():
# Allow user to select a directory and store it in global var
# called folder_path
global folder_path
filename = filedialog.askdirectory()
folder_path.set(filename)
print(filename)
root = Tk()
folder_path = StringVar()
lbl1 = Label(master=root,textvariable=folder_path)
lbl1.grid(row=0, column=1)
button2 = Button(text="Browse", command=browse_button)
button2.grid(row=0, column=3)
mainloop()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With