Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an efficient way to tell if text is selected in a Tkinter Text widget?

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
like image 875
Brandon Avatar asked Dec 09 '10 14:12

Brandon


People also ask

Which method is related with tag of text widget?

tag_nextrange() . Use this method to change the order of tags in the tag stack (see Section 24.5, “ Text widget tags”, above, for an explanation of the tag stack). If you pass two arguments, the tag with name tagName is moved to a position just above the tag with name aboveThis .

What is get () in Tkinter?

An Entry widget in Tkinter is nothing but an input widget that accepts single-line user input in a text field. To return the data entered in an Entry widget, we have to use the get() method. It returns the data of the entry widget which further can be printed on the console.

Which widget is used to accept the text strings from the user?

The Entry widget is used to accept single-line text strings from a user.


1 Answers

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"
like image 55
Bryan Oakley Avatar answered Sep 21 '22 09:09

Bryan Oakley