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 the necessary modules

import tkinter as tk
import re
  • Create the main window and set its title

window = tk.Tk()
window.title("Text Editor with Autocompletion")
  • Create a text widget for user input

text_widget = tk.Text(window)
text_widget.pack()

Implementing Autocompletion

  • Load a dictionary of words −

dictionary = ["apple", "banana", "cherry", "dog", "elephant", "fruit", "grape", "house", "internet"]
  • Define a function to handle user input −

def handle_input(event):
   current_text = text_widget.get("insert linestart", "insert")
   current_word = re.findall(r'\w+', current_text)[-1] if re.findall(r'\w+', current_text) else ""
   suggestions = [word for word in dictionary if word.startswith(current_word)]
    
   if suggestions:
      autocomplete = suggestions[0]
      text_widget.insert("insert", autocomplete[len(current_word):])
      text_widget.focus_set()
  • Bind the function to the key press event −

text_widget.bind("<KeyRelease>", handle_input)

Testing the Autocompletion

  • Add the following code at the end to start the application −

window.mainloop()
  • Run the program, and a text editor window will appear.

  • Start typing words from the loaded dictionary, and you will notice autocompletion suggestions appearing as you type.

Example

Let’s checkout the complete code, its explanation, and the output −

# Import necessary libraries
import tkinter as tk
import re
# Create an instance of Tkinter Frame
window = tk.Tk()
# Set the geometry of Tkinter Frame
window.geometry("700x250")
# Set the title of Tkinter Frame
window.title("Text Editor with Autocompletion")
# Create a text widget for user input
text_widget = tk.Text(window)
text_widget.pack()
# Load a dictionary of words
dictionary = ["apple", "banana", "cherry", "dog", "elephant", "fruit", "grape", "house", "internet"]
# Define a function to handle user input
def handle_input(event):
   current_text = text_widget.get("insert linestart", "insert")
   current_word = re.findall(r'\w+', current_text)[-1] if re.findall(r'\w+', current_text) else ""
   suggestions = [word for word in dictionary if word.startswith(current_word)]
    
   if suggestions:
      autocomplete = suggestions[0]
      text_widget.insert("insert", autocomplete[len(current_word):])
      text_widget.focus_set()
# Bind the function to key press event
text_widget.bind("<KeyRelease>", handle_input)
window.mainloop()

Explanation

  • We start by importing the necessary modules, including tkinter for GUI operations and re for regular expressions.

  • Next, we create the main window and a text widget using the Tk() and Text() functions, respectively. The text widget is where the user can input text.

  • We define a list of words as our dictionary.

  • The handle_input function is responsible for handling user input. It is triggered by the <KeyRelease> event, which occurs when the user releases a key after pressing it.

  • Inside the handle_input function, we extract the current word from the text widget using regular expressions.

  • We then iterate over the dictionary and filter out the words that start with the current word. These filtered words are the suggestions for autocompletion.

  • If there are suggestions available, we take the first suggestion and insert the remaining part of the word into the text widget.

  • Finally, we call text_widget.focus_set() to ensure that the text widget remains in focus for continuous input.

  • The autocompletion functionality is implemented by binding the handle_input function to the key release event.

Output

When the program is run, the main window appears, and the user can start typing. As they type, the program suggests autocompletions based on the loaded dictionary and inserts the completion if available.

Conclusion

To conclude, we have successfully implemented text autocompletion in a Python/Tkinter-based text editor. By following the step-by-step guide, you can now enhance your text editor with this useful feature. The autocompletion functionality allows users to save time and effort by suggesting completions for partially typed words or phrases.

Throughout the implementation process, we set up the user interface using Tkinter, loaded a dictionary of words, and implemented the autocompletion logic. By binding the handle_input function to the key release event, we provided real-time suggestions based on the user's input.

Remember to customize the dictionary according to your specific needs, as it directly affects the autocompletion suggestions. You can further enhance the text editor by implementing additional features like syntax highlighting, code completion, or search functionalities.

By incorporating text autocompletion, you can significantly improve the user experience and productivity of your Python text editor. Happy coding!

Updated on: 06-Dec-2023

44 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements