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()
Jindil
  • 145
  • 1
  • 3
  • 9

1 Answers1

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.

Parviz Karimli
  • 1,247
  • 1
  • 14
  • 26
  • 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 :) – Jindil Aug 17 '16 at 20:35
  • What do you mean by several folder directory paths? You have not included it in your question. Please describe your problem more clearly. – Parviz Karimli Aug 18 '16 at 05:06
  • 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. – Jindil Aug 19 '16 at 15:06
  • Is your problem solved? – Parviz Karimli Aug 19 '16 at 15:45
  • Yes definitly, Should I mark it as resolved somehow ? Cant find the option... – Jindil Aug 21 '16 at 18:38
  • Which answer are you talking about? – Parviz Karimli Aug 21 '16 at 18:43
  • Can I make my file dialogue look better? It looks a little "Windows XP-y" – E.T. Jan 27 '17 at 23:39
  • @Jindil yes, in order to accept the answer please click the check mark at the upper-left hand corner of the answer. – Parviz Karimli May 01 '19 at 09:18
  • @Suyash, `from tkinter import *` imports everything from tkinter including filedialog, so your edit was not necessary. – Parviz Karimli Jan 26 '20 at 12:17