Copy To Clipboard Highlighted Text From Text Widget

Chris Angelico rosuav at gmail.com
Mon Mar 21 21:47:11 EDT 2016


On Tue, Mar 22, 2016 at 12:24 PM, Wildman via Python-list
<python-list at python.org> wrote:
> 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.

Fortunately your code reveals that you're using "tk" here, but
otherwise, please state up-front which GUI library you're using; there
are quite a few.

> 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.

You're trying to do one of two things:

1) Copy the selected text to the clipboard
2) If there isn't any, copy all the text.

So I would say yes, the basic layout of try/except to get the text is
perfect. However, DON'T use a bare "except:" clause. You'll get back a
specific exception; catch that instead. Other than that, sure, your
code looks fine.

ChrisA



More information about the Python-list mailing list