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 file")
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.askopenfilename(initialdir="./", title="AETies : select a file",filetypes=file_types)
via filedialod, askopenfilename() method will be called.
It will return the selected file path with name of file.
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.
- title = this helps to provide browse window a name.
- filetypes = here types of file to open can be provided, as mentioned below
file_types = (("python", "*.py"), ("text", "*.txt"), ("xml", "*.xml"), ("all_types", "*.*"))
now we will select a file
once you select the file name.
below is the full code to ask a file to browse, browse a file and show the path on screen.
#program
file_types = (("python", "*.py"), ("text", "*.txt"), ("xml", "*.xml"), ("all_types", "*.*"))
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.askopenfilename(initialdir="./", title="AETies : select a file",filetypes=file_types)
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 file")
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