I\'d like to be able to get a string out of a highlighted portion of text, how do I go about this?
use the get method. If you want the selected text use the indices SEL_FIRST and SEL_LAST.
[edit]] one of the comments speculated this didn't work with Tkinter because there was no attribute "sel". "sel" isn't an attribute, it's a tag. Tags are a remarkably powerful feature of the text widget.
Here's an example:
import Tkinter as tk
import tkFont
class App:
def __init__(self):
root=tk.Tk()
self.text = tk.Text(root)
self.text.pack()
self.button = tk.Button(root, text="Get Selection", command=self.OnButton)
self.button.pack()
root.mainloop()
def OnButton(self):
print "selected text: '%s'" % self.text.get(tk.SEL_FIRST, tk.SEL_LAST)
app=App()
For this demo to work, type some text in the text box then press the button.
For a Tkinter.Text or Tkinter.Entry widget, you can use:
content = text.selection_get()
Interactive example of getting selected text both from an Entry and from a Text widgets in the Python console:
>>> import Tkinter
>>> w = Tkinter.Tk()
>>> e = Tkinter.Entry(w)
>>> e.pack()
>>> t = Tkinter.Text(w)
>>> t.pack()
#(scribble at the widgets in the created window, and select text in the Entry)
>>> e.selection_get()
'1234'
#(select text)
>>> t.selection_get()
'1234'
>>>
According to Bryan Oakley's comment:
selection_getis a generic widget method available to all widgets. It does not always get the selected string from a Text widget. It might, but it's not guaranteed. What it does is get what's called the "X" selection (from tk's X11 roots). If you setexportselectionto False for the Text widget,selection_getwill fail to work. So your suggest will work in the normal case, but not in all cases.
The Text widget has a special tag named 'sel', accessible via Tkinter.SEL and testable via text_widget.tag_ranges(Tkinter.SEL), which allows you to retrieve the "selected" text. Here is a simple example:
if textWidget.tag_ranges(Tkinter.SEL):
print('SELECTED Text is %r' % textWidget.get(Tkinter.SEL_FIRST, Tkinter.SEL_LAST))
else:
print('NO Selected Text')
If you want a slightly more advanced solution, you can also try:
ranges = textWidget.tag_ranges(Tkinter.SEL)
if ranges:
print('SELECTED Text is %r' % textWidget.get(*ranges))
else:
print('NO Selected Text')