5

On this page describing the Tkinter text widget, it's stated that 'The selection is a special tag named SEL (or “sel”) that corresponds to the current selection. You can use the constants SEL_FIRST and SEL_LAST to refer to the selection. If there’s no selection, Tkinter raises a TclError exception.'

My question: is there a more efficient way to tell if there is a selection in a Text widget besides fooling with exceptions, like the below code?

seltext = None
try:
   seltext = txt.get(SEL_FIRST, SEL_LAST)
except TclError:
   pass

if seltext:
   # do something with text
Brandon
  • 3,684
  • 1
  • 18
  • 25

2 Answers2

10

You can ask the widget for the range of text that the "sel" tag encompases. If there is no selection the range will be of zero length:

if txt.tag_ranges("sel"):
    print "there is a selection"
else:
    print "there is no selection"
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • It should be noted that `tag_ranges` will return a list of ranges of text that have the tag name. So this can be useful if you need them (as I do at this particular moment, hence why I commented). – Brōtsyorfuzthrāx Oct 30 '14 at 03:38
1

Here's a way to check if a specified location is selected.

if "sel" in myTextWidget.tag_names(INSERT): #use 'not in' to see if it's not selected
    print("INSERT to 'insert+1c' is selected text!");

I don't know why they don't let you put a second index in there. I also don't know that this is any more efficient for the processor than your version, but it does seem to be more standard from what I can tell.

Brōtsyorfuzthrāx
  • 4,387
  • 4
  • 34
  • 56