Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve the filepath from a Browse-Button with askopenfilename and write it to an entry widget with Tkinter

Tags:

python

tkinter

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.

like image 216
user3432015 Avatar asked Dec 31 '25 12:12

user3432015


1 Answers

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()
like image 148
olymposeical Avatar answered Jan 03 '26 00:01

olymposeical



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!