Opening and reading a file with askopenfilename in Tkinter?

When a user wants to open a file from a directory, the preferred way to do this is to display a popup where the user selects a file to Open. Like most tools and widgets, Tkinter provides us a way to open a dialog for opening a file, reading a file, saving a file. All these functionalities are part of filedialog Module in Python. Just like other widgets, filedialog needs to be imported explicitly in the notebook. There are certain other modules that contain the filedialog such as, askdirectory, askopenfilename, askopenfile, askopenfilenames, asksaveasfilename, etc.


In this example, we will define a function to open and read the file using askopenfilename.

We will define an application which contains a button to open a file and will pack the content of the file in a Label widget. In order to read the file content, we will use the read() method along with the filename.

#Import tkinter library
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
#Create an instance of tkinter frame or window
win= Tk()
#Define a function to Opening the specific file using filedialog
def open_files():
   path= filedialog.askopenfilename(title="Select a file", filetypes=(("text files","*.txt"),
("all files","*.*")))

   file= open(path,'r')
   label.config(text=txt, font=('Courier 13 bold'))
#Create an Empty Label to Read the content of the File
label= Label(win,text="", font=('Courier 13 bold'))
#Create a button for opening files
button=ttk.Button(win, text="Open",command=open_files)


Running the above code will display a window which contains a button which when clicked, will open a new window to load and read the file content.

Click the "Open" button to open the file(text, "*") in the window.