Clipboard use with Python-TK

Russell E. Owen owen_nospam at astro.omitme.washington.edu
Mon Aug 21 14:55:41 EDT 2000


You can send tk_textPaste, tk_textCopy and tk_textCut to the text object as follows:
    def doCut (self, evt=None):
        widget = self.focus_get()
        if isinstance(widget, Entry):
            if widget.selection_present():
                widget.clipboard_clear()
                widget.clipboard_append(widget.selection_get())
                widget.delete(SEL_FIRST, SEL_LAST)
        else:
            # works for Text, not for Entry (why?); fails quietly
            widget.tk.call('tk_textCut', widget._w)

    def doCopy (self, evt=None):
        widget = self.focus_get()
        if isinstance(widget, Entry):
            if widget.selection_present():
                widget.clipboard_clear()
                widget.clipboard_append(widget.selection_get())
        else:
            # works for Text, not for Entry (why?); fails quietly
            widget.tk.call('tk_textCopy', widget._w)

    def doPaste (self, evt=None):
        widget = self.focus_get()
        # works for Text and Entry, at least; fails quietly
        widget.tk.call('tk_textPaste', widget._w)

If you are using the default menus, you will find that they already send the virtual events <<Cut>>, <<Copy>> and <<Paste>>, in which case bind the above methods to these events. Note that the virtual events are sent to the parent window, not to the widget, hence the use of self.focus_get() instead of extracting the widget from the event. If you are defining your own menus, you can define them to send these events or you can define them to call these methods directly.

-- Russell

P.S. This solution is thanks to help from John Grayson (how to send messages) and from the book Effective Tcl and Tk Programming (that these messages exist).

In article <966847084.1209576451 at news.club-internet.fr>, Bellamy Bruno <bellamy at freesurf.fr> wrote:

>Hi there... :)
>
>I'm working on a little text editor project in Python using TK, but I'm
>confused about the syntax when using the clipboard. So far, I didn't get any
>result and couldn't find a complete description of this in Python-TK
>documentations.
>Does anyone has some code sample about how to copy, cut and
>paste text to (and from!) the clipboard, when using the TK text object?



More information about the Python-list mailing list