On Tue, 22 Mar 2016 12:47:11 +1100, Chris Angelico wrote:

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

Noted.

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

Yes, that is exactly it.

> 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

Thanks.  I changed the code as you (and MRAB) suggested.

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

Works perfectly.  Thanks again.

-- 
<Wildman> GNU/Linux user #557453
"Our country's founders cherished liberty, not democracy."
  -Ron Paul
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to