Text Editor (Notepad) in Python
About the project: This is a project for a a fully functional text editor, or "Notepad," built with Python using the tkinter library. It includes core features like opening, saving, and creating new files.
All the code is in a single file, so you can easily run it without any complex setup.
How to Run the App
- Save the Code:Save the code above into a file named `simple_notepad.py`.
- Run from Terminal: Open your terminal or command prompt, navigate to the folder where you saved the file, and run the command:
python simple_notepad.py
- This will launch the graphical notepad window.
This simple text editor provides a solid foundation. You could expand on this project by adding more advanced features such as find and replace functionality, font and color customization, or line numbering.
Project Level: Intermediate
You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.
Steps: Follow these stepsStep 1: Copy below code using green 'copy' button.
Step 2: Paste the code on your chosen editor.
Step 3: Save the code with filename and .py extention.
Step 4: Run (Press F5 if using python IDLE).
# simple_notepad.py
import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext
import os
class NotepadApp:
"""
A simple notepad application built using Python's Tkinter library.
It provides basic text editing functionalities like creating, opening,
and saving text files.
"""
def __init__(self, root):
self.root = root
self.root.title("Python Notepad")
self.root.geometry("800x600")
# Current file path, initially None
self.current_file = None
# --- Text Widget ---
# A scrolled text widget is used to allow for text longer than the window size.
self.text_area = scrolledtext.ScrolledText(
self.root,
wrap=tk.WORD,
font=("Consolas", 12),
undo=True,
padx=5,
pady=5
)
self.text_area.pack(expand=True, fill='both')
# --- Menu Bar ---
self.menu_bar = tk.Menu(self.root)
self.root.config(menu=self.menu_bar)
# File Menu
self.file_menu = tk.Menu(self.menu_bar, tearoff=0)
self.menu_bar.add_cascade(label="File", menu=self.file_menu)
self.file_menu.add_command(label="New", command=self.new_file)
self.file_menu.add_command(label="Open...", command=self.open_file)
self.file_menu.add_command(label="Save", command=self.save_file)
self.file_menu.add_command(label="Save As...", command=self.save_as_file)
self.file_menu.add_separator()
self.file_menu.add_command(label="Exit", command=self.exit_app)
# Edit Menu
self.edit_menu = tk.Menu(self.menu_bar, tearoff=0)
self.menu_bar.add_cascade(label="Edit", menu=self.edit_menu)
self.edit_menu.add_command(label="Undo", command=self.text_area.edit_undo)
self.edit_menu.add_command(label="Redo", command=self.text_area.edit_redo)
self.edit_menu.add_separator()
self.edit_menu.add_command(label="Cut", command=lambda: self.text_area.event_generate("<>"))
self.edit_menu.add_command(label="Copy", command=lambda: self.text_area.event_generate("<>"))
self.edit_menu.add_command(label="Paste", command=lambda: self.text_area.event_generate("<>"))
# --- Status Bar ---
self.status_bar = tk.Label(self.root, text="Ready", bd=1, relief=tk.SUNKEN, anchor=tk.W)
self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
# Set initial status and title
self.update_status("Welcome!")
self.update_title()
# Bind keyboard shortcuts
self.root.bind('<Control-n>', self.new_file)
self.root.bind('<Control-o>', self.open_file)
self.root.bind('<Control-s>', self.save_file)
def update_title(self, file_path=None):
"""Updates the window title with the current file name."""
if file_path:
file_name = os.path.basename(file_path)
self.root.title(f"{file_name} - Python Notepad")
else:
self.root.title("Untitled - Python Notepad")
def update_status(self, message):
"""Updates the status bar with a given message."""
self.status_bar.config(text=message)
def new_file(self, event=None):
"""Creates a new, blank file."""
self.current_file = None
self.text_area.delete(1.0, tk.END)
self.update_title()
self.update_status("New file created.")
def open_file(self, event=None):
"""Opens an existing file from the file system."""
file_path = filedialog.askopenfilename(
defaultextension=".txt",
filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]
)
if file_path:
try:
with open(file_path, "r") as file:
content = file.read()
self.text_area.delete(1.0, tk.END)
self.text_area.insert(tk.END, content)
self.current_file = file_path
self.update_title(file_path)
self.update_status(f"Opened: {os.path.basename(file_path)}")
except Exception as e:
messagebox.showerror("Error", f"Failed to open file: {e}")
self.update_status("Failed to open file.")
def save_file(self, event=None):
"""Saves the current file, prompting for a new name if it's unsaved."""
if self.current_file:
try:
with open(self.current_file, "w") as file:
file.write(self.text_area.get(1.0, tk.END))
self.update_status(f"Saved: {os.path.basename(self.current_file)}")
except Exception as e:
messagebox.showerror("Error", f"Failed to save file: {e}")
self.update_status("Failed to save file.")
else:
self.save_as_file()
def save_as_file(self, event=None):
"""Saves the current file to a new location."""
file_path = filedialog.asksaveasfilename(
defaultextension=".txt",
filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]
)
if file_path:
self.current_file = file_path
self.save_file()
self.update_title(file_path)
def exit_app(self):
"""Exits the application after confirming with the user."""
if messagebox.askyesno("Exit", "Are you sure you want to exit?"):
self.root.destroy()
if __name__ == "__main__":
root = tk.Tk()
app = NotepadApp(root)
root.mainloop()
← Back to Projects