Reputation: 43
I'd like to be able to get the index (like 1.1...) out of a highlighted text in a Tkinter text box, any ideas?
Upvotes: 3
Views: 3753
Reputation: 385980
The selected text has the tag "sel". The beginning and ending range of the selected text is defined by "sel.first"
and "sel.last"
. You can use those directly if you want to get the text, like so:
chars = the_text_widget.get("sel.first", "sel.last")
If, instead, you want the numerical index, you can use the index
method which converts any index to its canonical form:
s0 = the_text_widget.index("sel.first")
s1 = the_text_widget.index("sel.last")
Note: the tkinter module defines constants for these: SEL_FIRST
and SEL_LAST
but I personally see no reason to use these constants. Using their string counterparts is just as easy and helps reinforce the notion that the selection is just another tag without any special properties.
Upvotes: 9