Copy To Clipboard Highlighted Text From Text Widget

Wildman best_lay at yahoo.com
Mon Mar 21 21:24:31 EDT 2016


I have a gui that has text widget and I want to be able to
copy to the clipboard the text that is highlighted or the
text widget's entire contents if no text is highlighted.
This line of code works for the highlighted text:

    text2copy = self.text.get(tk.SEL_FIRST, tk.SEL_LAST)

However, this code will generate an exception if no text
is highlighted.  So here is what I come up with and it
works:

def copy_clipboard(self):
    try:
        text2copy = self.text.get(tk.SEL_FIRST, tk.SEL_LAST)
    except:
        text2copy = self.text.get()
    root.clipboard_clear()
    root.clipboard_append(text2copy)

My concern is whether or not this approach is acceptable.
Is it ok to let the exception occur or would it be better
to avoid it?  If the later, I would appreciate suggestions
on how to do that, I mean how to determine if any text is
highlighted without generating an exception.  My research
was not very fruitful.

-- 
<Wildman> GNU/Linux user #557453
May the Source be with you.



More information about the Python-list mailing list