3

I'm just started playing around with Tkinter. I would like to have a small window with an entry.widget and a browse button right next to it, where a file path can be entered or a file can be selected by clicking on the "Browse" button. Here is my first approach:

from Tkinter import *
import tkFileDialog
#import os

master = Tk()

def callback():
    path = tkFileDialog.askopenfilename()
    print path

w = Label(master, text="File Path:")
e = Entry(master)
b = Button(master,text="Browse", command = callback)

w.pack(side=LEFT)
e.pack(side=LEFT)
b.pack(side=LEFT)

master.mainloop()

My problem is, I do not know how to write the file path to the entry widget after a file has been selected. I think it might work with something like

e.insert(path)

but I can't access path since it is only a local variable in the callback function. I already tried assigning it as a global variable but it didn't work out.

Thank you in advance for any advise.

2 Answers 2

3

Using the 'insert':

from Tkinter import *
import tkFileDialog

master = Tk()


def callback():
    path = tkFileDialog.askopenfilename()
    e.delete(0, END)  # Remove current text in entry
    e.insert(0, path)  # Insert the 'path'
    # print path


w = Label(master, text="File Path:")
e = Entry(master, text="")
b = Button(master, text="Browse", command=callback)

w.pack(side=LEFT)
e.pack(side=LEFT)
b.pack(side=LEFT)

master.mainloop()
Sign up to request clarification or add additional context in comments.

Comments

2

You can use a Tkinter.StringVar for your entry:

var = StringVar()
e = Entry(master, textvariable=var)
b = Button(master, text="Browse",
           command=lambda:var.set(tkFileDialog.askopenfilename()))

Comments

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.