Pasting in the Tkinter Text widget Pasting in the Tkinter Text widget tkinter tkinter

Pasting in the Tkinter Text widget


You don't need to use event_generate if you're going to pre-process the data. You simply need to grab the clipboard contents, manipulate the data, then insert it into the widget. To fully mimic paste you also need to delete the selection, if any.

Here's a quick example, barely tested:

import Tkinter as tkfrom Tkinter import TclErrorclass SampleApp(tk.Tk):    def __init__(self, *args, **kwargs):        tk.Tk.__init__(self, *args, **kwargs)        self.text = tk.Text(self, width=40, height=8)        self.button = tk.Button(self, text="do it!", command=self.doit)        self.button.pack(side="top")        self.text.pack(side="bottom", fill="both", expand=True)        self.doit()    def doit(self, *args):        # get the clipboard data, and replace all newlines        # with the literal string "\n"        clipboard = self.clipboard_get()        clipboard = clipboard.replace("\n", "\\n")        # delete the selected text, if any        try:            start = self.text.index("sel.first")            end = self.text.index("sel.last")            self.text.delete(start, end)        except TclError, e:            # nothing was selected, so paste doesn't need            # to delete anything            pass        # insert the modified clipboard contents        self.text.insert("insert", clipboard)if __name__ == "__main__":    app = SampleApp()    app.mainloop()

When you run this code and click on the "do it!" button, it will replace the selected text with what was on the clipboard after converting all newlines to the literal sequence \n