Certainly! Here's a simple notepad app created using Python and the Tkinter library:
import tkinter as tk
from tkinter import filedialog
class Notepad:
def __init__(self, master):
self.master = master
master.title("Notepad")
self.text_area = tk.Text(master, wrap=tk.WORD)
self.text_area.pack(expand=True, fill=tk.BOTH)
self.create_menu()
def create_menu(self):
menu_bar = tk.Menu(self.master)
file_menu = tk.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="New", command=self.new_file)
file_menu.add_command(label="Open", command=self.open_file)
file_menu.add_command(label="Save", command=self.save_file)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=self.master.quit)
menu_bar.add_cascade(label="File", menu=file_menu)
self.master.config(menu=menu_bar)
def new_file(self):
self.text_area.delete(1.0, tk.END)
def open_file(self):
file_path = filedialog.askopenfilename(defaultextension=".txt", filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")])
if file_path:
self.text_area.delete(1.0, tk.END)
with open(file_path, "r") as file:
self.text_area.insert(tk.END, file.read())
def save_file(self):
file_path = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")])
if file_path:
with open(file_path, "w") as file:
file.write(self.text_area.get(1.0, tk.END))
root = tk.Tk()
notepad = Notepad(root)
root.mainloop()
This code creates a simple notepad app with the following features:
- A text area where the user can enter and edit text.
- A menu bar with a "File" menu that contains the following options:
- "New": Clears the text area.
- "Open": Opens a file dialog to select a text file and loads its content into the text area.
- "Save": Opens a file dialog to save the content of the text area to a file.
- "Exit": Closes the notepad app.
Here's how the code works:
- We import the necessary modules:
tkinter for creating the GUI and filedialog for handling file dialogs.
- We define a
Notepad class that represents the notepad app.
- In the
__init__ method, we set up the main window, create a text area, and call the create_menu method to create the menu bar.
- The
create_menu method sets up the menu bar with a "File" menu and its corresponding options.
- The
new_file method clears the text area.
- The
open_file method opens a file dialog to select a text file and loads its content into the text area.
- The
save_file method opens a file dialog to save the content of the text area to a file.
- Finally, we create an instance of the
Notepad class and start the main event loop.
When you run this code, a window will appear with a text area and a menu bar. You can use the "File" menu to create a new file, open an existing file, save the current content to a file, or exit the app.
Note: Make sure you have Python and the Tkinter library installed on your system to run this code.