How to Create a Notepad using Python

Free Python courses with 57 real-time projects - Learn Python

Today we are going to learn how to build your text editor like Notepad using python. This is a detailed tutorial with code and explanation using which you will be able to create your text editor.

About Notepad

As you must be already aware, Notepad is a simple text editor for Microsoft Windows that allows users to create text documents, save them as plain text, and edit plaintext files. It is extremely useful for viewing or writing relatively short text documents saved as plain text.

  • The File menu has options like New, Open, Save, Save As, and Exit.
  • The Edit menu has options like Cut, Copy, Paste, Delete, Find, Select All, and Time/Date.
  • The Help menu has options like About Notepad.

Download Notepad Python Code

Please download the source code of text editor / notepad: Notepad Python Project Code

Steps to create a Notepad using Python

Import required packages and libraries

#importing required packages and libraries

import re
from tkinter import *
from tkinter.ttk import *
from datetime import datetime
from tkinter import messagebox
from tkinter import filedialog,simpledialog
from tkinter.scrolledtext import ScrolledText

To start with, we first import the required packages and libraries into our python program. We will use Tkinter to design our notepad GUI. The package ‘re’ is for regular expressions, which we will use later to implement functionalities in the ‘Edit’ menu option for our notepad.

We import ‘datetime’ to display the time and date in the ‘Edit’ menu.

Initialize the GUI window

#the root widget
root = Tk()
root.title('DataFlair Notepad')
root.resizable(0, 0)

#creating scrollable notepad window
notepad = ScrolledText(root, width = 90, height = 40)
fileName = ' '

After importing all the libraries and packages, we initialize the GUI window with the title Python Notepad. I have made the window size fixed by passing values (0,0) to the resizable function. We use the ScrolledText function to make our notepad window scrollable as more text gets added.

Define Functions

#defining functions for commands
def cmdNew():     #file menu New option
    global fileName
    if len(notepad.get('1.0', END+'-1c'))>0:
        if messagebox.askyesno("Notepad", "Do you want to save changes?"):
            cmdSave()
        else:
            notepad.delete(0.0, END)
    root.title("Notepad")

def cmdOpen():     #file menu Open option
    fd = filedialog.askopenfile(parent = root, mode = 'r')
    t = fd.read()     #t is the text read through filedialog
    notepad.delete(0.0, END)
    notepad.insert(0.0, t)
    
def cmdSave():     #file menu Save option
    fd = filedialog.asksaveasfile(mode = 'w', defaultextension = '.txt')
    if fd!= None:
        data = notepad.get('1.0', END)
    try:
        fd.write(data)
    except:
        messagebox.showerror(title="Error", message = "Not able to save file!")
     
def cmdSaveAs():     #file menu Save As option
    fd = filedialog.asksaveasfile(mode='w', defaultextension = '.txt')
    t = notepad.get(0.0, END)     #t stands for the text gotten from notepad
    try:
        fd.write(t.rstrip())
    except:
        messagebox.showerror(title="Error", message = "Not able to save file!")

def cmdExit():     #file menu Exit option
    if messagebox.askyesno("Notepad", "Are you sure you want to exit?"):
        root.destroy()

def cmdCut():     #edit menu Cut option
    notepad.event_generate("<<Cut>>")

def cmdCopy():     #edit menu Copy option
    notepad.event_generate("<<Copy>>")

def cmdPaste():     #edit menu Paste option
    notepad.event_generate("<<Paste>>")

def cmdClear():     #edit menu Clear option
    notepad.event_generate("<<Clear>>")
       
def cmdFind():     #edit menu Find option
    notepad.tag_remove("Found",'1.0', END)
    find = simpledialog.askstring("Find", "Find what:")
    if find:
        idx = '1.0'     #idx stands for index
    while 1:
        idx = notepad.search(find, idx, nocase = 1, stopindex = END)
        if not idx:
            break
        lastidx = '%s+%dc' %(idx, len(find))
        notepad.tag_add('Found', idx, lastidx)
        idx = lastidx
    notepad.tag_config('Found', foreground = 'white', background = 'blue')
    notepad.bind("<1>", click)

def click(event):     #handling click event
    notepad.tag_config('Found',background='white',foreground='black')

def cmdSelectAll():     #edit menu Select All option
    notepad.event_generate("<<SelectAll>>")
    
def cmdTimeDate():     #edit menu Time/Date option
    now = datetime.now()
    # dd/mm/YY H:M:S
    dtString = now.strftime("%d/%m/%Y %H:%M:%S")
    label = messagebox.showinfo("Time/Date", dtString)

def cmdAbout():     #help menu About option
    label = messagebox.showinfo("About Notepad", "Notepad by - \nDataFlair")

Next, we define functions for the File menu, Edit menu, and Help menu of our notepad.

  • The File menu has options like New, Open, Save, Save As, and Exit.
  • The Edit menu will have the options Cut, Copy, Paste, Delete, Find, Select All and Time/Date.
  • The Help menu item will have the option About Notepad that just displays some basic text and information.

Python Tkinter provides a set of functions that we can use while working with files. By using these, we do not have to design standard dialogues by ourselves. I have opened a file and saved the file using the filedialog library.

The messagebox widget in Tkinter is used to display the message boxes in the python applications. It has several functions that we can use to display appropriate messages. I have used the askyesno and showerror functions.

Add Commands

#notepad menu items
notepadMenu = Menu(root)
root.configure(menu=notepadMenu)

#file menu
fileMenu = Menu(notepadMenu, tearoff = False)
notepadMenu.add_cascade(label='File', menu = fileMenu)

#adding options in file menu
fileMenu.add_command(label='New', command = cmdNew)
fileMenu.add_command(label='Open...', command = cmdOpen)
fileMenu.add_command(label='Save', command = cmdSave)
fileMenu.add_command(label='Save As...', command = cmdSaveAs)
fileMenu.add_separator()
fileMenu.add_command(label='Exit', command = cmdExit)

#edit menu
editMenu = Menu(notepadMenu, tearoff = False)
notepadMenu.add_cascade(label='Edit', menu = editMenu)

#adding options in edit menu
editMenu.add_command(label='Cut', command = cmdCut)
editMenu.add_command(label='Copy', command = cmdCopy)
editMenu.add_command(label='Paste', command = cmdPaste)
editMenu.add_command(label='Delete', command = cmdClear)
editMenu.add_separator()
editMenu.add_command(label='Find...', command = cmdFind)
editMenu.add_separator()
editMenu.add_command(label='Select All', command = cmdSelectAll)
editMenu.add_command(label='Time/Date', command = cmdTimeDate)

#help menu
helpMenu = Menu(notepadMenu, tearoff = False)
notepadMenu.add_cascade(label='Help', menu = helpMenu)

#adding options in help menu
helpMenu.add_command(label='About Notepad', command = cmdAbout)

Tkinter has predefined virtual events which can be used using the event_generate function. I have used the events <<Cut>>, <<Copy>>, <<Paste>>, <<Clear>>, and <<SelectAll>> to implement the options available in the edit menu of python notepad.

The find function is to find a given string or substring from the text in the notepad. The TimeDate function is to display the current time and date to the user.

We will be using all these functions when we add commands to our menu options for File, Edit, and Help. This is why we have named the functions as cmdNew, cmdSave, cmdOpen, etc. where cmd is an abbreviation for command. This makes the code more understandable and readable.

notepad.pack()
root.mainloop()

The last thing we need to do is to add the menu options in notepad for File, Edit, and Help, and then add specific commands to these menus. While creating the menus using the Menu function, the parameter ‘tearoff = False’ is to prevent Tkinter from adding a dotted line in the menu which is added by default.

We label the commands using the ‘label’ parameter. This is how the menu option will appear to the user. The ‘command’ parameter is used to assign the functions that we created earlier, that will define how the command will behave.

Finally ‘root.mainloop()’ is a method on the main window that runs our application. This method will continuously loop, it will wait for events from the user till the user exits the program.

When we close the window that we have created, we will see a new prompt is displayed in the python shell.

Python Notepad Output Screenshots

python notepad screenshot

python notepad text-editor screenshot

Conclusion

We have successfully developed a text editor / notepad using python. Along with a simple notepad we have developed file, edit, and help menu. In this python project, we have used tkinter and basic python concepts.

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

follow dataflair on YouTube

2 Responses

  1. Shashank says:

    How to encrypt the text entered in the notepad and save the file with encrypted text in the file.

  2. poncho says:

    thank 🧒

Leave a Reply

Your email address will not be published. Required fields are marked *