5

I have been reading through several posts regarding to Browse button issues in Tkinter but I could not find my answer.

So I have wrote this code to get a directory path when clicking the browse button, and displaying this path in an entry field. It woks partly : a file browser window directly pops up when I run the script. I indeed get the path in the entry field but if I want then to change the folder using my Browse button it does not work.

I dont want to have the browser poping up right from the start but only when I click on Browse ! Thanks for your answers

from Tkinter import *
from tkFileDialog import askdirectory

window = Tk() # user input window

MyText= StringVar()

def DisplayDir(Var):
    feedback = askdirectory()
    Var.set(feedback)

Button(window, text='Browse', command=DisplayDir(MyText)).pack()
Entry(window, textvariable = MyText).pack()
Button(window, text='OK', command=window.destroy).pack()

mainloop()
0

1 Answer 1

12

This is so easy -- you need to assign the path to a variable and then print it out:

from tkinter import *
root = Tk()

def browsefunc():
    filename = filedialog.askopenfilename()
    pathlabel.config(text=filename)

browsebutton = Button(root, text="Browse", command=browsefunc)
browsebutton.pack()

pathlabel = Label(root)
pathlabel.pack()

P.S.: This is in Python 3. But the concept is same.

Sign up to request clarification or add additional context in comments.

9 Comments

Alright, Thanks. But I actually need to get several folder directory paths and in this case it works only for the variable 'pathlabel'. I will try with the lambda instead :)
What do you mean by several folder directory paths? You have not included it in your question. Please describe your problem more clearly.
Yes sorry I had simplified the script to the minimum but I have designed a formular in which I gather some user inputs including intger, files and folders that's why it was interesting to have a generic command. Finally I have in my button command = lambda: DisplayDir(MyText) as suggested in Bryan's post link.
Is your problem solved?
Yes definitly, Should I mark it as resolved somehow ? Cant find the option...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.