Browsing file and getting filepath in entrybox in Tkinter

lsr729 picture lsr729 · Aug 7, 2019 · Viewed 9.1k times · Source

I am trying to make a simple GUI using Tkinter in python2, in which I need to make an entry box and a button besides that. The button browses the file and shows the filepath in the entrybox. How can I do that.

I used the tkFileDialog.askopenfilename that allows to browse the path but how can I make the gui to show that path in an entry box.

I tried it as follows:

import tkinter as tk
import tkFileDialog

root=tk.Tk()
def browsefunc():
    filename =tkFileDialog.askopenfilename(filetypes=(("tiff files","*.tiff"),("All files","*.*")))

ent1=tk.Entry(frame,font=40)
ent1.grid(row=2,column=2)

b1=tk.Button(frame,text="DEM",font=40,command=browsefunc)
b1.grid(row=2,column=4)

root.mainloop()

Attached a screenshot of what I needs. Attached is the screenshot for desired GUI

Answer

TornaxO7 picture TornaxO7 · Aug 7, 2019

Are you really sure, that you are using python2? Because you wrote tkinter with a lowercase t and not with an uppercase T or did you just write it wrong?.

Anyway, you can easily insert a little text (in your case a path) into your Entry-widget by using the insert method of the Entry-widget. In your case it would be:

import Tkinter as tk
import tkFileDialog

root=tk.Tk()    

ent1=tk.Entry(root,font=40)
ent1.grid(row=2,column=2)

def browsefunc():
    filename =tkFileDialog.askopenfilename(filetypes=(("tiff files","*.tiff"),("All files","*.*")))
    ent1.insert(tk.END, filename) # add this

b1=tk.Button(root,text="DEM",font=40,command=browsefunc)
b1.grid(row=2,column=4)

root.mainloop()

The tk.END parameter gives the last index of the entry-string back.
If you already wrote something into the Entry-Widget like that:

This is my path:

and you add your path, than it will looks like that:

This is my path:/usr/bin/... 

As you can see it adds the string in the end of the "entry-string".
The other option would be 0 for the index than your path will be in the beginning of the entry-widget:

/usr/bin...HI

I'm sorry if my english is horrible! Feel free to edit it!