Here we will be learning how to browse a file and collect file path in Python Tkinter.
To browse a file we need to import filedialog from tkinter
from tkinter import filedialog
below is the code to create a browse button and file path entry widget
mw = Tk()
mw.geometry('500x50+100+100')
mw.title("AETies : Automation Expert Technologies")
sel_file = Label(mw, text='file', padx=5).pack(side=LEFT)
file_path = Entry(mw, width=42, fg='grey')
file_path.insert(0, "Please select a directory")
file_path.pack(side=LEFT)
browse_Button = Button(mw, text=' Browse ', fg='red', command=browse_file, padx=5).pack(side=LEFT)
mainloop()
once we click on browse button, we will call browse_file function, inside which filedialog will perform operation to ask file to open
below is the code
select_file_path = filedialog.askdirectory(initialdir="./", title='AETies : select a directory')
via filedialod, askdirectory() method will be called.
It will return the selected directory path.
lets talk about options to pass
- initialdir = this will accept a path, to be open for browse window, like any particular folder or self directory.
Once you click on Browse button
once you selected any directory
below is the full code
#program
try :
from Tkinter import * # supports Python 2
except:
from tkinter import * # supports Python 3
from tkinter import filedialog
def browse_file():
file_path.delete(0, END)
file_path.config(fg='black')
select_file_path = filedialog.askdirectory(initialdir="./", title='AETies : select a directory')
file_path.insert(0, select_file_path)
mw = Tk()
mw.geometry('500x50+100+100')
mw.title("AETies : Automation Expert Technologies")
sel_file = Label(mw, text='file', padx=5).pack(side=LEFT)
file_path = Entry(mw, width=42, fg='grey')
file_path.insert(0, "Please select a directory")
file_path.pack(side=LEFT)
browse_Button = Button(mw, text=' Browse ', fg='red', command=browse_file, padx=5).pack(side=LEFT)
mainloop()
also check
Comments
Post a Comment