Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()
like image 602
Jindil Avatar asked Aug 16 '16 13:08

Jindil


1 Answers

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.

like image 86
Parviz Karimli Avatar answered Nov 04 '22 22:11

Parviz Karimli