Display Path of a file in Tkinter using "browse" Button - Python

Jindil picture Jindil · Aug 16, 2016 · Viewed 39.1k times · Source

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()

Answer

Parviz Karimli picture Parviz Karimli · Aug 16, 2016

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.