How to Read a Text File and Display the Contents in a Tkinter With Python?

In this tutorial, I will explain in detail how to read a text file and display the contents in a Tkinter with Python. As a software developer working on a project for New York clients, I recently needed to create a Tkinter app that could open a user-specified text file and output the contents into a text area in the interface. I will walk through the steps I took to accomplish this common programming task.

Read a Text File and Display the Contents in a Tkinter With Python

Let us understand the step by step process to read and display the content of text files with Python Tkinter.

Read How to Cancel Scheduled Functions with after_cancel() in Python Tkinter?

1. Set up the Basic Tkinter App

To get started, let’s create a simple Tkinter application with a button to trigger opening the file and a text area to display the file contents. Here’s the basic code:

import tkinter as tk

def open_file():
    pass
  
window = tk.Tk()
window.title("Text File Reader")

btn_open = tk.Button(window, text="Open Text File", command=open_file) 
btn_open.pack()

txt_edit = tk.Text(window)
txt_edit.pack()

window.mainloop()

This sets up a window with an “Open Text File” button and an empty text area. The open_file() function will contain the logic to read the file, but for now, it does nothing.

Check out How to Create GUI Layouts with Python Tkinter Separator?

2. Read the Text File Contents

Now let’s implement reading data from a text file in Python. The built-in open() function allows opening a file. We’ll use the with statement to automatically close the file after reading:

def open_file():
    filepath = "example.txt"
    with open(filepath, "r") as file:
        data = file.read()
        txt_edit.insert(tk.END, data)

This opens the text file located at filepath in read mode, reads the entire contents into the data variable, and inserts that text into the Tkinter text area txt_edit.

Read How to Add Functions to Python Tkinter?

3. Allow the User to Select a File

Rather than hard-coding the file path, let’s give the user the ability to select which text file to open. The filedialog module in Tkinter provides this functionality:

from tkinter import filedialog

def open_file():
    filepath = filedialog.askopenfilename(filetypes=[("Text Files", "*.txt")])
    if not filepath:
        return
    with open(filepath, "r") as file:
        data = file.read()
        txt_edit.delete("1.0", tk.END)  
        txt_edit.insert(tk.END, data)

Now when the Open button is clicked, a file dialog pops up prompting the user to select a text file. The selected file path is stored in filepath. We check that a file was chosen before proceeding.

The text area is cleared txt_edit.delete() before inserting the new file contents. This replaces any previously loaded text.

Check out How to Create a Filter() Function in Python Tkinter?

4. Display the File Path

Let’s display the path of the currently loaded file in the window title bar:

def open_file():
    filepath = filedialog.askopenfilename(filetypes=[("Text Files", "*.txt")])
    if not filepath:
        return
    window.title(f"Text File Reader - {filepath}")
    with open(filepath, "r") as file: 
        data = file.read()
        txt_edit.delete("1.0", tk.END)
        txt_edit.insert(tk.END, data)  

The window.title() method sets the title of the Tkinter window. We include the filepath in the title so the user knows which file is displayed.

Check out How to Create a Python Tkinter Panel with Search Functionality?

5. Handle Errors

One issue I ran into was that my program would crash if the user tried to open a non-text file or a file that didn’t exist. To prevent this, I wrapped the file opening logic in a try/except block:

def open_file():
    filepath = filedialog.askopenfilename(filetypes=[("Text Files", "*.txt")]) 
    if not filepath:
        return
    try:
        with open(filepath, "r") as file:
            data = file.read()
            window.title(f"Text File Reader - {filepath}")  
            txt_edit.delete("1.0", tk.END)
            txt_edit.insert(tk.END, data)
    except:
        window.title(f"Text File Reader")
        txt_edit.delete("1.0", tk.END)
        txt_edit.insert(tk.END, "Failed to read file \n'{filepath}'")

Now if any error occurs while trying to read the file (e.g. wrong format or file not found), the title bar reverts to the default and the text area displays an error message noting the file path that failed.

Read How to Create Scrollable Frames with Python Tkinter?

The Complete Example Code

Here is the final complete code for the text file reading the Tkinter app:

import tkinter as tk 
from tkinter import filedialog

def open_file():
    """Open a file for editing."""
    filepath = filedialog.askopenfilename(
        filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]
    )
    if not filepath:
        return
    try:
        with open(filepath, mode="r", encoding="utf-8") as input_file:
            text = input_file.read()
            window.title(f"Text Editor Application - {filepath}")
            txt_edit.delete(1.0, tk.END)
            txt_edit.insert(tk.END, text)
    except OSError:
        window.title("Text Editor Application")
        txt_edit.delete(1.0, tk.END)  
        txt_edit.insert(tk.END, f"Failed to read file \n'{filepath}'")

window = tk.Tk()
window.title("Text File Viewer")

window.rowconfigure(0, minsize=800, weight=1)
window.columnconfigure(1, minsize=800, weight=1)

txt_edit = tk.Text(window)
fr_buttons = tk.Frame(window, relief=tk.RAISED, bd=2)
btn_open = tk.Button(fr_buttons, text="Open", command=open_file)

btn_open.grid(row=0, column=0, sticky="ew", padx=5, pady=5)
fr_buttons.grid(row=0, column=0, sticky="ns")  
txt_edit.grid(row=0, column=1, sticky="nsew")

window.mainloop()

And here’s what the final Tkinter app looks like:

Read a Text File and Display the Contents in a Tkinter With Python

You now have a fully functional Tkinter GUI application that can read and display the contents of user-selected text files. The techniques used here, like filedialog for selecting files and open() for reading file contents, apply to many other Python apps you may want to create. I hope you found this tutorial helpful! Let me know if you have any other questions.

Check out How to Display Images in Python Tkinter?

Conclusion

In this tutorial, I helped you learn how to read a text file and display the contents in a Tkinter with Python. I explained step by step the process of setting up the basic Tkinter app, reading the text file contents, allowing the user to select a file, displaying the file path, and handling errors, I have also given full code which gives accurate output.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.