Create a text file reader in python

In this tutorial we are going to create a text file reader which will read in words from a file and then shows them under the label of that file reader ui. First of all lets create the ui of the text file reader with the help of tkinter.

import tkinter as tk
from tkinter import ttk
import tkinter.font as Font

win = tk.Tk()
win.title("Text Reader")

aLabel = ttk.Label(win, text="   Click the button to load the greeting!", width=33,
                   font=Font.Font(family="Helvetica", size=13))  # This is where the text will be loaded
aLabel.grid(column=0, row=1)

# The callback function of the button
def clickMe():
   # empty for now

# Adding a Button
action = ttk.Button(win, text="Click!", command=clickMe)  # When the button get clicked the text will be loaded onto the label
action.grid(column=0, row=0)

win.mainloop()  # run the main loop

The above program will create the file reader ui as follows…

The UI of file reader
The UI of file reader

Next add in this import statement so we can use the askopenfilename module to create a file chooser.

from tkinter.filedialog import askopenfilename

Next we need to make thing happen, under the clickMe function add in below code which will open a file chooser so you can pick a file (after you have clicked the above button) for the program to read in that file content and displays them under the label of the file reader.

# The callback function of the button
def clickMe():
    filename = askopenfilename(title = "Select text file")
    fin = open(filename, 'rt')
    sometext = fin.read()
    fin.close()
    aLabel.configure(text=sometext)

After you have clicked the button the file chooser will open, now select a text file from the hard disk to display it’s content onto the label.

The text displays onto the label
The text displays onto the label

We will continue more on the tkinter module so stay tune!

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of