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.

Programmatically, we can divide it in two parts shown below −

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 −

text_widget.tag_add("my_tag", "1.0", "1.5")

In this code, a tag named "my_tag" 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. Here's a step-by-step example of how to do it −

sel_start, sel_end = text_widget.tag_ranges("sel")

if sel_start and sel_end:
   selected_text = text_widget.get(sel_start, sel_end)
   print("Selected Text:", selected_text)

In this code, sel_start and sel_end store the start and end indices of the selected text. If there is selected text, the get() method retrieves it, and we print it to the console. If there's no selected text, we display a message indicating that nothing is selected.

Example

To demonstrate how to extract selected text from a Tkinter Text widget, let’s create a basic Python application in which we'll create a Tkinter window, add a Text widget, a button for getting the selected text, and a label to display the result.

# importing the tkinter module
import tkinter as tk

# defining the function to select and extract text from text widget
def get_selected_text():
   sel_start, sel_end = text_widget.tag_ranges("sel")
    
   if sel_start and sel_end:
      selected_text = text_widget.get(sel_start, sel_end)
      result_label.config(text="Selected Text: " + selected_text)
   else:
      result_label.config(text="No text selected.")

# creating Tkinter window
root = tk.Tk()
root.geometry("720x450")
root.title("Extracting Selected Text from Python Tkinter Text Widget")

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

# creating the text button
get_text_button = tk.Button(root, text="Get Selected Text", command=get_selected_text)
get_text_button.pack()

result_label = tk.Label(root, text="")
result_label.pack()

root.mainloop()

In this code, we create a Tkinter window and add a Text widget to it. We also introduce a button labeled "Get Selected Text" and a label that will display the result.

Output

Once you run the code, a simple GUI will appear, consisting of a Text widget, a button labeled "Get Selected Text," and a label. Users can type or paste text into the Text widget and select a portion of it. Clicking the "Get Selected Text" button will display the selected text in the result label.

You can see, we selected the text “tutorialspoint.com” and when clicked on the Get Selected Text button, it is displayed.

Conclusion

Extracting selected text from a Tkinter Text widget is a fundamental operation in GUI application development. Whether you're building a simple text selection tool or a sophisticated text editor, the ability to access and manipulate selected text is essential for providing a rich user experience.

In this article, we've explored how to select and retrieve text from a Tkinter Text widget using the tag_ranges("sel") method. We've created a simple Python application that demonstrates the process of selecting text and displaying it to the user.

Updated on: 05-Dec-2023

252 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements