Tkinter question: cut, copy and paste?

John Grayson johngrayson at home.com
Thu Aug 10 19:24:20 EDT 2000


In article <8mv769$178a$1 at nntp6.u.washington.edu>,
  "Russell E. Owen" <owen at astroNOJNK.washington.edu.invalid> wrote:
> I'm trying to figure out how to implement standard cut, copy and
paste
> support for Tkinter's widgets (especially Enter and Text).
>
> I happen to be working on a Mac (MacPython 1.5.2). The Edit menu is
> displayed, but the operations don't have any effect. I assume this is
> true of other platforms as well?
>
> By experimenting I have found:
>
> The existing Edit menu Cut, Copy and Paste items do send the expected
> virtual events <<Cut>>, <<Copy>> and <<Paste>>, as described in
Harrison
> & McLennan's excellent "Effective Tcl/Tk Programming".
>
> Harrison & McLennan go on to suggest binding to these events and
calling
> "Tk library procedures" tk_textCut, tk_textCopy and tk_textPaste to
> command the widget do the right thing. This sounds perfect, but I
have
> not found any way to get to these via Tkinter.
>
> So, instead, I tried doing without these handy-sounding library
> procedures. So far it's been like hitting my head against a brick
wall.
> It's easy enough to get the appropriate widget (the event is sent to
a
> window, not a widget, but focus_get obtains the widget). But the
trick
> is telling that widget what to do! I can get the currently selected
text
> with selection_get, and presumably I can copy that to the clipboard,
but
> what about Cut? There is no general command to delete the selected
text
> (selection_clear eliminates the selection but doesn't affect the
text).
> There are ways to do it in the Text widget, but they are specific to
> Text. I've not figured out any way to cut the selected text from the
> Entry widget. And having to hand-code each type of widget seems a bit
> crazy anyway.
>
> So...how do you enable Cut, Copy and Paste in Tkinter?
>
> -- Russell
>


I played around for a few minutes:

See if this example gives you some clues. Note that you *can* call
Tk routines from Tkinter...

from Tkinter import *

class Paster:
    def __init__(self, master):
        self.master = master
        self.master.clipboard_clear()
        self.e1 = Entry(master, width=40)
        self.e1.pack(side=TOP, padx=10, pady=10)
        self.e2 = Entry(master, width=40)
        self.e2.pack(side=TOP, padx=10, pady=10)
        Label(master,
              text='Type in top entry, select text - Ctrl-C - hit
Paste').pack()
        Button(master, text='Paste',
               command=self.pasteit).pack(anchor=CENTER)

    def pasteit(self, *event):
        self.master.tk.call('tk_textPaste', self.e2._w)

root = Tk()
p = Paster(root)
root.mainloop()


   John Grayson


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list