How to Open, Read, and Save Text Files Using Python and Tkinter
In this Python tutorial we will create an application that allows users to open, read, and save text files using the Tkinter library for the graphical user interface.
The application features a text editor and a menu bar for file operations, including open, save, and exit options.
What We Are Gonna Use In This Project:
- Python Programming Language.- Tkinter for GUI.
- VS Code Editor.
- VS Code Editor.
Project Source Code:
import tkinter as tk
from tkinter import ttk, filedialog
class TextFile_OpenReadSave:
def __init__(self, master):
# Initialize the main application
self.master = master
master.title("Open Read Save Text File")
# Styling
master.geometry("600x400")
master.configure(bg="#f0f0f0")
# Create a Text widget for text editing
self.text_editor = tk.Text(master)
self.text_editor.pack(expand=True, fill=tk.BOTH)
# Create a menu bar
self.menubar = tk.Menu(master)
# Create a File menu in the menu bar
self.file_menu = tk.Menu(self.menubar, tearoff=0)
# Add commands to the File menu
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_separator()
self.file_menu.add_command(label="Exit", command = master.quit)
# Add the File menu to the menu bar
self.menubar.add_cascade(label="File", menu=self.file_menu)
# Configure the menu bar for the main window
master.config(menu=self.menubar)
def open_file(self):
# Ask user to select a file for opening
file_path = filedialog.askopenfilename(filetypes=[("Text Files", "*.txt"),
("All Files", "*.*")])
if file_path:
# Read the contents of the selected file and insert it into the text editor
with open(file_path, "r") as file:
self.text_editor.delete("1.0", tk.END)
self.text_editor.insert(tk.END, file.read())
def save_file(self):
# Ask user to select a file for saving
file_path = filedialog.asksaveasfilename(defaultextension=".txt",
filetypes=[("Text Files", "*.txt"),("All Files", "*.*")])
if file_path:
# Write the contents of the text editor to the selected file
with open(file_path, "w") as file:
file.write(self.text_editor.get("1.0", tk.END))
if __name__ == "__main__":
root = tk.Tk()
app = TextFile_OpenReadSave(root)
root.mainloop()