Python Tkinter Program for Reading Text Files

Posted by

Text File Reader Program using Tkinter in Python

Text File Reader Program using Tkinter in Python

In this article, we will create a simple Text File Reader Program using Tkinter in Python. Tkinter is a standard GUI toolkit for Python and it is very easy to use. With Tkinter, we can create GUI applications like text editors, file browsers, and many more.

Here is the code for the Text File Reader Program:

import tkinter as tk
from tkinter import filedialog

def open_file():
    file_path = filedialog.askopenfilename()
    with open(file_path, 'r') as file:
        text = file.read()
        text_box.delete('1.0', tk.END)
        text_box.insert('1.0', text)

root = tk.Tk()
root.title("Text File Reader")

btn = tk.Button(root, text="Open File", command=open_file)
btn.pack()

text_box = tk.Text(root)
text_box.pack()

root.mainloop()

In this program, we first import the necessary modules, tkinter and filedialog. We then define a function open_file() that opens a file dialog using filedialog.askopenfilename() and reads the content of the selected file. We then update the text in the Text widget using text_box.delete() and text_box.insert() methods.

We create a Tkinter window by creating an instance of the tk.Tk() class. We set the title of the window to “Text File Reader”. We then create a Button widget using tk.Button() that calls the open_file() function when clicked. We also create a Text widget using tk.Text() to display the content of the selected text file.

To run the program, simply copy and paste the code into a Python script and run it. The program will open a window where you can click the “Open File” button to select a text file to read.

That’s it! You have created a simple Text File Reader Program using Tkinter in Python. You can further customize the program by adding features like saving the text content to a file or adding functionalities like search and replace.