Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #105433

Re: Copy To Clipboard Highlighted Text From Text Widget

From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Subject Re: Copy To Clipboard Highlighted Text From Text Widget
Date 2016-03-22 12:47 +1100
Message-ID <mailman.478.1458611235.12893.python-list@python.org> (permalink)
References <s6ednccPwOtSA23LnZ2dnUU7-bOdnZ2d@giganews.com>

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Copy To Clipboard Highlighted Text From Text Widget Wildman <best_lay@yahoo.com> - 2016-03-21 20:24 -0500
  Re: Copy To Clipboard Highlighted Text From Text Widget Chris Angelico <rosuav@gmail.com> - 2016-03-22 12:47 +1100
    Re: Copy To Clipboard Highlighted Text From Text Widget Wildman <best_lay@yahoo.com> - 2016-03-21 22:36 -0500
      Re: Copy To Clipboard Highlighted Text From Text Widget Chris Angelico <rosuav@gmail.com> - 2016-03-22 14:46 +1100
  Re: Copy To Clipboard Highlighted Text From Text Widget MRAB <python@mrabarnett.plus.com> - 2016-03-22 02:01 +0000
    Re: Copy To Clipboard Highlighted Text From Text Widget Wildman <best_lay@yahoo.com> - 2016-03-21 22:31 -0500

csiph-web