Python > Advanced Topics and Specializations > Specific Applications (Overview) > GUI Development (Tkinter, PyQt, Kivy)

Tkinter Simple Text Editor

This snippet demonstrates a basic text editor built with Tkinter. It includes features for opening, saving, and editing text files. This provides a practical example of GUI programming principles, including event handling, widget placement, and file I/O.

Complete Code

This code defines a TextEditor class that creates a simple text editor GUI using Tkinter. It includes functions to open, save, and save as files. The GUI consists of a text area for editing and a menu bar with 'File' and 'Help' options. Error handling is implemented to display messages if file operations fail.

import tkinter as tk
from tkinter import filedialog, messagebox

class TextEditor:
    def __init__(self, master):
        self.master = master
        master.title("Simple Text Editor")

        self.text_area = tk.Text(master, wrap=tk.WORD)
        self.text_area.pack(expand=tk.YES, fill=tk.BOTH)

        self.menu_bar = tk.Menu(master)
        self.file_menu = tk.Menu(self.menu_bar, tearoff=0)
        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_file_as)
        self.file_menu.add_separator()
        self.file_menu.add_command(label="Exit", command=master.quit)
        self.menu_bar.add_cascade(label="File", menu=self.file_menu)

        self.help_menu = tk.Menu(self.menu_bar, tearoff=0)
        self.help_menu.add_command(label="About", command=self.show_about)
        self.menu_bar.add_cascade(label="Help", menu=self.help_menu)

        master.config(menu=self.menu_bar)

        self.filename = None

    def open_file(self):
        self.filename = filedialog.askopenfilename(defaultextension=".txt",
                                                  filetypes=[("Text Files", "*.txt"),
                                                             ("All Files", "*.*")]
                                                  )
        if self.filename:
            try:
                with open(self.filename, "r") as f:
                    self.text_area.delete(1.0, tk.END)
                    self.text_area.insert(tk.END, f.read())
            except Exception as e:
                messagebox.showerror("Error", f"Could not open file: {e}")

    def save_file(self):
        if self.filename:
            try:
                with open(self.filename, "w") as f:
                    f.write(self.text_area.get(1.0, tk.END))
            except Exception as e:
                messagebox.showerror("Error", f"Could not save file: {e}")
        else:
            self.save_file_as()

    def save_file_as(self):
        self.filename = filedialog.asksaveasfilename(defaultextension=".txt",
                                                    filetypes=[("Text Files", "*.txt"),
                                                               ("All Files", "*.*")]
                                                    )
        if self.filename:
            try:
                with open(self.filename, "w") as f:
                    f.write(self.text_area.get(1.0, tk.END))
            except Exception as e:
                messagebox.showerror("Error", f"Could not save file: {e}")

    def show_about(self):
        messagebox.showinfo("About", "Simple Text Editor using Tkinter")


root = tk.Tk()
editor = TextEditor(root)
root.mainloop()

Concepts Behind the Snippet

The snippet illustrates core GUI programming concepts:

  • Widget Creation: Creating Tkinter widgets like Text, Menu, and associating them with the main window.
  • Layout Management: Using pack to arrange widgets within the window.
  • Event Handling: Associating menu commands with functions (e.g., clicking 'Open' triggers open_file).
  • File I/O: Reading and writing data to files using Python's built-in file handling.
  • Dialog Boxes: Using filedialog and messagebox for user interaction.

Real-Life Use Case

This snippet provides a foundation for building more complex text-based applications. It can be extended for:

  1. Syntax Highlighting: Adding color coding to the text area based on language syntax.
  2. Find and Replace: Implementing search and replace functionality.
  3. Line Numbering: Displaying line numbers alongside the text.
  4. Integration with Version Control Systems: Adding features to interact with Git or other VCS.

Best Practices

  • Object-Oriented Programming: The code is organized using a class, which promotes code reusability and maintainability.
  • Error Handling: try...except blocks are used to gracefully handle potential file I/O errors.
  • User-Friendly Interface: Dialog boxes provide clear feedback to the user.
  • Modularity: Breaking down the application into smaller, manageable functions.

When to Use Tkinter

Tkinter is suitable for:

  • Simple GUI applications.
  • Cross-platform applications that don't require a highly customized look and feel.
  • Rapid prototyping of GUI concepts.
  • Learning GUI programming fundamentals.

Alternatives

Alternatives to Tkinter include PyQt, Kivy, and wxPython. PyQt offers more advanced widgets and customization options but has a steeper learning curve. Kivy is designed for multi-touch applications. wxPython provides a native look and feel on different platforms.

Pros

  • Comes standard with Python.
  • Simple and easy to learn.
  • Cross-platform compatible.

Cons

  • Limited set of widgets compared to other frameworks.
  • Less visually appealing compared to other frameworks.
  • Can be difficult to create complex layouts.

FAQ

  • How do I change the font size?

    You can change the font size by modifying the tk.Text widget's configuration. For example: self.text_area = tk.Text(master, wrap=tk.WORD, font=('Arial', 12)). You can adjust the font family and size as needed.
  • How do I add a status bar?

    You can add a status bar using a tk.Label widget placed at the bottom of the window. Update the label's text to display relevant information (e.g., file name, cursor position).