开发者

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

开发者 https://www.devze.com 2023-01-29 22:53 出处:网络
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开发者_JAVA百科 use the con

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开发者_JAVA百科 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


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"


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消