Simple Notepad with file menu (use of Tkinter Library)

 import tkinter as tk

from tkinter import scrolledtext

from tkinter import filedialog


def new_file():

    text_area.delete(1.0, tk.END)

    root.title("Untitled")


def open_file():

    file_path = filedialog.askopenfilename()

    if file_path:

        with open(file_path, "r") as file:

            text = file.read()

            text_area.delete(1.0, tk.END)

            text_area.insert(tk.END, text)

        root.title(file_path)


def save_file():

    file_path = filedialog.asksaveasfilename(defaultextension=".txt")

    if file_path:

        with open(file_path, "w") as file:

            text = text_area.get(1.0, tk.END)

            file.write(text)

        root.title(file_path)


root = tk.Tk()

root.title("Simple Notepad")


text_area = scrolledtext.ScrolledText(root, wrap=tk.WORD)

text_area.pack(expand=True, fill=tk.BOTH)


menu_bar = tk.Menu(root)

file_menu = tk.Menu(menu_bar, tearoff=0)

file_menu.add_command(label="New", command=new_file)

file_menu.add_command(label="Open", command=open_file)

file_menu.add_command(label="Save", command=save_file)

file_menu.add_separator()

file_menu.add_command(label="Exit", command=root.quit)

menu_bar.add_cascade(label="File", menu=file_menu)


root.config(menu=menu_bar)


root.mainloop()



Comments