Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Implement text-autocompletion in Python/Tkinter based text editor
Text autocompletion is a useful feature that enhances productivity and improves the user experience in text editors. It automatically suggests completions for partially typed words or phrases, reducing the effort required for manual typing.
In this article, we will explore how to implement text autocompletion in a Python text editor using the Tkinter library. We will walk through the process step by step, including setting up the user interface, handling user input, and implementing the autocompletion functionality.
Prerequisites
To follow along with this tutorial, you should have a basic understanding of Python programming and the Tkinter library. Additionally, make sure you have Python and Tkinter installed on your system.
Setting Up the User Interface
Import Required Modules
First, import the necessary modules for GUI operations and regular expressions ?
import tkinter as tk import re
Create the Main Window
Create the main window and configure its properties ?
import tkinter as tk
window = tk.Tk()
window.title("Text Editor with Autocompletion")
window.geometry("700x400")
Add Text Widget
Create a text widget where users can input text ?
import tkinter as tk
window = tk.Tk()
window.title("Text Editor with Autocompletion")
window.geometry("700x400")
text_widget = tk.Text(window, wrap=tk.WORD, font=("Arial", 12))
text_widget.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
window.mainloop()
Implementing Autocompletion Logic
Dictionary Setup
Define a dictionary of words for autocompletion suggestions ?
# Sample dictionary of words
dictionary = [
"apple", "application", "banana", "cherry", "computer",
"development", "dog", "elephant", "fruit", "grape",
"house", "internet", "javascript", "keyboard", "language",
"mouse", "network", "orange", "programming", "python"
]
Input Handler Function
Create a function to handle user input and provide autocompletion ?
import tkinter as tk
import re
def handle_input(event):
# Get current line text up to cursor position
current_text = text_widget.get("insert linestart", "insert")
# Extract the current word being typed
words = re.findall(r'\w+', current_text)
current_word = words[-1].lower() if words else ""
# Skip autocompletion for very short words
if len(current_word) < 2:
return
# Find matching suggestions
suggestions = [word for word in dictionary if word.lower().startswith(current_word)]
# Auto-complete with first suggestion
if suggestions and suggestions[0].lower() != current_word:
autocomplete = suggestions[0]
remaining_text = autocomplete[len(current_word):]
# Insert the remaining part
text_widget.insert("insert", remaining_text)
# Select the inserted text for easy replacement
text_widget.tag_add("sel", f"insert-{len(remaining_text)}c", "insert")
text_widget.mark_set("insert", f"insert-{len(remaining_text)}c")
Complete Implementation
Full Working Example
Here's the complete text editor with autocompletion functionality ?
import tkinter as tk
import re
# Dictionary of words for autocompletion
dictionary = [
"apple", "application", "banana", "cherry", "computer",
"development", "dog", "elephant", "fruit", "grape",
"house", "internet", "javascript", "keyboard", "language",
"mouse", "network", "orange", "programming", "python"
]
def handle_input(event):
# Get current line text up to cursor position
current_text = text_widget.get("insert linestart", "insert")
# Extract the current word being typed
words = re.findall(r'\w+', current_text)
current_word = words[-1].lower() if words else ""
# Skip autocompletion for very short words
if len(current_word) < 2:
return
# Find matching suggestions
suggestions = [word for word in dictionary if word.lower().startswith(current_word)]
# Auto-complete with first suggestion
if suggestions and suggestions[0].lower() != current_word:
autocomplete = suggestions[0]
remaining_text = autocomplete[len(current_word):]
# Insert the remaining part
text_widget.insert("insert", remaining_text)
# Select the inserted text for easy replacement
text_widget.tag_add("sel", f"insert-{len(remaining_text)}c", "insert")
text_widget.mark_set("insert", f"insert-{len(remaining_text)}c")
# Create main window
window = tk.Tk()
window.title("Text Editor with Autocompletion")
window.geometry("700x400")
# Create text widget
text_widget = tk.Text(window, wrap=tk.WORD, font=("Arial", 12))
text_widget.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# Bind the autocompletion handler
text_widget.bind("<KeyRelease>", handle_input)
# Add instructions
instructions = tk.Label(window, text="Start typing words like 'app', 'prog', or 'comp' to see autocompletion in action!",
bg="lightblue", pady=5)
instructions.pack(fill=tk.X)
# Start the application
window.mainloop()
How It Works
The autocompletion system works through these key components:
Event Binding: The <KeyRelease> event triggers the autocompletion function whenever a key is released.
Word Extraction: Regular expressions extract the current word being typed from the text widget.
Suggestion Matching: The system searches the dictionary for words that start with the current partial word.
Text Insertion: When a match is found, the remaining characters are inserted and selected for easy replacement.
Key Features
This implementation includes several important features:
Real-time autocompletion as you type
Case-insensitive matching
Minimum word length requirement (2 characters)
Text selection for easy replacement
Customizable word dictionary
Conclusion
We have successfully implemented text autocompletion in a Python/Tkinter text editor. The system provides real-time word suggestions based on a customizable dictionary, improving typing efficiency and user experience. You can enhance this further by adding features like multiple suggestions, context-aware completion, or loading dictionaries from external files.
