19

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()
2
  • 1
    You have stored it in a variable. It is stored in filename. If you wish to store for other functions to use, then you should use a. Classes b. Global variables. I'll provide an example of a Global variable below. Commented Apr 20, 2017 at 9:59
  • great! Using global variable it worked! thanks!! Commented Apr 20, 2017 at 10:01

2 Answers 2

36

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
    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()
Sign up to request clarification or add additional context in comments.

Comments

-2
   def browse_drive(self):
        drive = filedialog.askopenfilename(initialdir='C:/', title="Select System Drive")  # Open file dialog
        if drive:
            drive_letter, _ = os.path.splitdrive(drive)
            if drive_letter:
                self.drive_letter = drive_letter.upper()  # Extract and convert drive letter to uppercase
                self.drive_entry.delete(0, tk.END)
                self.drive_entry.insert(0, self.drive_letter)
            else:
                messagebox.showerror("Error", "Please select a valid system drive.")

2 Comments

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
Add some context. For example, how is this better than scotty's answer or what does it do differently that the original poster would need or what are the advantages of this version? Remember, not only the one asking the question reads these answers, but even people not having an account here and looking for answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.