Uploaded by husseinmubiru2024

Python Tkinter Notepad Tutorial: Build a Simple Text Editor

advertisement
Creating a simple Notepad using Python and the `tkinter` library is a great project. Here's a
complete example:
```python
import tkinter as tk
from tkinter import Text, filedialog, messagebox
# Function to open a file
def open_file():
file_path = filedialog.askopenfilename(filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")])
if file_path:
with open(file_path, 'r') as file:
text_area.delete(1.0, tk.END)
text_area.insert(tk.END, file.read())
# Function to save a file
def save_file():
file_path = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=[("Text Files",
"*.txt"), ("All Files", "*.*")])
if file_path:
with open(file_path, 'w') as file:
file.write(text_area.get(1.0, tk.END))
# Function to exit the application
def exit_app():
root.quit()
# Create the main window
root = tk.Tk()
root.title("Simple Notepad")
root.geometry("800x600")
# Create the text area
text_area = Text(root, wrap='word')
text_area.pack(expand='yes', fill='both')
# Create a menu bar
menu_bar = tk.Menu(root)
root.config(menu=menu_bar)
# Create a file menu and add it to the menu bar
file_menu = tk.Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label="File", menu=file_menu)
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=exit_app)
# Start the main event loop
root.mainloop()
```
### Explanation:
1. **Importing Modules**: Import the necessary `tkinter` modules for creating the GUI and
handling file dialogs.
2. **File Operations**: Define functions `open_file` and `save_file` to handle opening and saving
text files, respectively. Use `filedialog.askopenfilename` and `filedialog.asksaveasfilename` to
open and save files.
3. **Exit Application**: Define `exit_app` function to close the application.
4. **Creating the Main Window**: Create the main application window and set its title and size.
5. **Text Area**: Create a `Text` widget for the text area and pack it to fill the window.
6. **Menu Bar**: Create a menu bar and a file menu with options to open, save, and exit. Add
the file menu to the menu bar and configure the main window to use this menu bar.
7. **Main Event Loop**: Start the `tkinter` main event loop with `root.mainloop()` to run the
application.
This simple Notepad application allows you to open, edit, and save text files. You can extend
this application by adding more features like cut, copy, paste, find, and replace functionalities.
Download