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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With