Simple Notepad With Tk (tkinter)


Here's a simple text file editor written in Python with the tkinter standard module. The program is made up of a simple window, a menu bar menu bar and a tk.Text widget to display the content of the files. To allow the user to browse files , the tkinter.filedialog standard module is used. Text files are written to and read via the standard pathlib.Path class. The code includes type annotations, so it requires Python 3.9 or higher. The rest is enough commented below.

from typing import Optional
from tkinter import filedialog, messagebox
from pathlib import Path
import tkinter as tk
class Notepad(tk.Tk):
    def __init__(self) -> None:
        self.menubar = tk.Menu()
        self.file_menu = tk.Menu(tearoff=False)
            label="Save As...",
        self.menubar.add_cascade(menu=self.file_menu, label="File")
        # Main widget to edit a text file.
        self.text = tk.Text()
        self.text.pack(expand=True, fill=tk.BOTH)
        # The `current_file` attribute contains the path of the
        # file that is being edited or `None` if the file has
        # not been saved yet.
        self.current_file: Optional[Path] = None
        # File types that will show in the open and save
        # file dialogs.
        self.filetypes: tuple[tuple[str, str], ...] = (
            ("Text Files", "*.txt"),
            ("All Files", "*.*")
        # Replace Tk's default behaviour to the event that
        # closes the window so we can save the file before
        # exiting the program.
        self.protocol("WM_DELETE_WINDOW", self.close)
    def close(self) -> None:
        if not self.can_continue():
        # Destroy the window.
    def set_current_file(self, current_file: Path) -> None:
        self.current_file = current_file
        self.title( + " - Notepad")
    def can_continue(self) -> bool:
        if self.text.edit_modified():
            result = messagebox.askyesnocancel(
                title="Unsaved Changes",
                message="Do you want to save changes?"
            cancel = result is None
            save_before = result is True
            if cancel:
                return False
            elif save_before:
            return True
        # If there were no editions, continue without saving.
        return True
    def new(self) -> None:
        if not self.can_continue():
        # Delete the previous text.
        self.text.delete("1.0", tk.END)
        self.current_file = None
    def open(self) -> None:
        filename = filedialog.askopenfilename(filetypes=self.filetypes)
        if not filename or not self.can_continue():
        # Remove previous text and load the new one.
        self.text.delete("1.0", tk.END)
        file = Path(filename)
        self.text.insert("1.0", file.read_text("utf8"))
        # Reset text state when a new file is opened.
    def save_current_file(self) -> None:
        if self.current_file is None:
        self.current_file.write_text(self.text.get("1.0", tk.END), "utf8")
    def save(self) -> None:
        if self.current_file is None:
    def save_as(self) -> None:
        filename = filedialog.asksaveasfilename(
        # Do nothing if the user closed or cancelled the dialog.
        if not filename:
notepad = Notepad()