On Tue, 22 Mar 2016 02:01:53 +0000, MRAB wrote: > On 2016-03-22 01:47, 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. >> >>> 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. >> > It'll raise TclError.
Thanks, that saved me some research time. -- <Wildman> GNU/Linux user #557453 "It is a dangerous notion that we need a government to protect us from ourselves." -Ron Paul -- https://mail.python.org/mailman/listinfo/python-list