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:Text
, Menu
, and associating them with the main window.pack
to arrange widgets within the window.open_file
).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:
Best Practices
try...except
blocks are used to gracefully handle potential file I/O errors.
When to Use Tkinter
Tkinter is suitable for:
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
Cons
FAQ
-
How do I change the font size?
You can change the font size by modifying thetk.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 atk.Label
widget placed at the bottom of the window. Update the label's text to display relevant information (e.g., file name, cursor position).