How to get selected text from Python Tkinter Text widget?

In the world of software development, graphical user interfaces (GUIs) are the key to creating user-friendly applications. Python, a popular programming language, offers various tools and libraries to make GUI application development accessible. Tkinter, one such library, simplifies the process of building GUI applications in Python.

In this article, we will explore a specific aspect of Tkinter how to easily extract selected text from a Tkinter Text widget.

A Closer Look at Tkinter

Tkinter, short for "Tk interface," is Python's go-to library for creating GUIs. It's widely used because it's included in most Python installations, making it extremely accessible. Tkinter provides a range of widgets, including buttons, labels, entry fields, and the Text widget, which is perfect for displaying and editing text.

The Tkinter Text widget shines when it comes to handling multi-line text. It offers various methods and options to customize its behavior, from changing fonts and colors to adding scrollbars. Among its many features, the ability to select and manipulate text within the widget is crucial.

Selecting Text in a Tkinter Text Widget

Selecting text in a Tkinter Text widget is the simplest part. Users can click and drag the mouse cursor to highlight text, just like they would in a regular text editor. You can also select text programmatically using the tag_add() method, which attaches tags to the desired text. These tags are like labels you can use to identify specific parts of the text.

For instance, here's how you can programmatically select text in a Tkinter Text widget ?

import tkinter as tk

root = tk.Tk()
text_widget = tk.Text(root)
text_widget.pack()

# Insert some sample text
text_widget.insert("1.0", "Hello, World! This is a sample text.")

# Programmatically select text from position 1.0 to 1.5
text_widget.tag_add("sel", "1.0", "1.5")

root.mainloop()

In this code, a tag named "sel" is applied to text starting from index "1.0" to index "1.5". This effectively selects text from the beginning of the first line (line 1) up to the fifth character on that line.

Getting the Selected Text

To retrieve the selected text from a Tkinter Text widget, you can use the tag_ranges("sel") method. This method provides the start and end indices of the selected text as a tuple. With these indices, you can easily get the selected text using the get() method ?

import tkinter as tk

def get_selected():
    try:
        # Get the indices of selected text
        start = text_widget.index(tk.SEL_FIRST)
        end = text_widget.index(tk.SEL_LAST)
        selected_text = text_widget.get(start, end)
        print("Selected Text:", selected_text)
    except tk.TclError:
        print("No text selected")

root = tk.Tk()
text_widget = tk.Text(root, height=5, width=40)
text_widget.pack(pady=10)

# Insert sample text
text_widget.insert("1.0", "Hello World!\nSelect some text and click the button.")

button = tk.Button(root, text="Get Selected Text", command=get_selected)
button.pack(pady=5)

root.mainloop()
Selected Text: Hello

Complete Example Application

Let's create a more comprehensive application that demonstrates how to extract selected text from a Tkinter Text widget ?

import tkinter as tk
from tkinter import messagebox

def get_selected_text():
    try:
        # Get selected text using SEL_FIRST and SEL_LAST
        start_pos = text_widget.index(tk.SEL_FIRST)
        end_pos = text_widget.index(tk.SEL_LAST)
        selected_text = text_widget.get(start_pos, end_pos)
        
        if selected_text:
            result_label.config(text=f"Selected Text: {selected_text}")
        else:
            result_label.config(text="No text selected.")
    except tk.TclError:
        # No selection made
        result_label.config(text="No text selected.")

def clear_selection():
    text_widget.tag_remove(tk.SEL, "1.0", tk.END)
    result_label.config(text="")

# Create main window
root = tk.Tk()
root.title("Text Selection Example")
root.geometry("500x400")

# Create Text widget
text_widget = tk.Text(root, height=10, width=50, wrap=tk.WORD)
text_widget.pack(pady=10, padx=10)

# Insert sample text
sample_text = """Welcome to TutorialsPoint!
This is a sample text widget.
Select any portion of this text and click 'Get Selected Text' to see it displayed below.
You can also clear the selection using the Clear button."""

text_widget.insert("1.0", sample_text)

# Create buttons
button_frame = tk.Frame(root)
button_frame.pack(pady=5)

get_button = tk.Button(button_frame, text="Get Selected Text", command=get_selected_text)
get_button.pack(side=tk.LEFT, padx=5)

clear_button = tk.Button(button_frame, text="Clear Selection", command=clear_selection)
clear_button.pack(side=tk.LEFT, padx=5)

# Result label
result_label = tk.Label(root, text="Select some text and click 'Get Selected Text'", 
                       wraplength=450, justify=tk.LEFT)
result_label.pack(pady=10, padx=10)

root.mainloop()

Alternative Methods

There are two main approaches to get selected text from a Text widget ?

Method Code Exception Handling
tag_ranges("sel") text_widget.tag_ranges("sel") Returns empty tuple if no selection
SEL_FIRST/SEL_LAST text_widget.index(tk.SEL_FIRST) Raises TclError if no selection

Key Points

When working with selected text in Tkinter Text widgets, keep these important points in mind:

  • Selection indices: Use "1.0" format where first number is line, second is character position
  • Error handling: Always handle cases where no text is selected using try-except blocks
  • Selection tags: The special "sel" tag represents the current selection
  • Clearing selection: Use tag_remove(tk.SEL, "1.0", tk.END) to clear selection programmatically

Conclusion

Extracting selected text from a Tkinter Text widget is a fundamental operation in GUI application development. Use text_widget.index(tk.SEL_FIRST) and text_widget.index(tk.SEL_LAST) with proper exception handling for reliable text selection functionality.

Updated on: 2026-04-02T17:24:31+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements