WORD PAD TEXT EDITOR
import tkinter as tk
from tkinter import filedialog, messagebox
class WordPad:
def __init__(self, root):
self.root = root
self.root.title("Word Pad")
self.root.geometry("800x600")
# Initialize the text area
self.text_area = tk.Text(self.root, undo=True)
self.text_area.pack(fill=tk.BOTH, expand=1)
# Initialize the 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.root.quit)
# 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=self.cut_text)
self.edit_menu.add_command(label="Copy", command=self.copy_text)
self.edit_menu.add_command(label="Paste", command=self.paste_text)
# Help menu
self.help_menu = tk.Menu(self.menu_bar, tearoff=0)
self.menu_bar.add_cascade(label="Help", menu=self.help_menu)
self.help_menu.add_command(label="About", command=self.show_about)
self.file_path = None
def new_file(self):
self.text_area.delete(1.0, tk.END)
self.file_path = None
def open_file(self):
self.file_path = filedialog.askopenfilename(filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")])
if self.file_path:
with open(self.file_path, "r") as file:
self.text_area.delete(1.0, tk.END)
self.text_area.insert(tk.END, file.read())
def save_file(self):
if self.file_path:
with open(self.file_path, "w") as file:
file.write(self.text_area.get(1.0, tk.END))
else:
self.save_as_file()
def save_as_file(self):
self.file_path = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")])
if self.file_path:
with open(self.file_path, "w") as file:
file.write(self.text_area.get(1.0, tk.END))
def cut_text(self):
self.text_area.event_generate("<>")
def copy_text(self):
self.text_area.event_generate("<>")
def paste_text(self):
self.text_area.event_generate("<>")
def show_about(self):
messagebox.showinfo("About", "Word Pad\nCreated using Tkinter")
if __name__ == "__main__":
root = tk.Tk()
app = WordPad(root)
root.mainloop()
No comments:
Post a Comment