Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pasting in the Tkinter Text widget

I'm using the line below to paste text in a Tkinter Text widget. However, I'd like to have the ability to alter the text prior to it being pasted. I'm specifically trying to remove anything that would cause a new line to be made (e.g., return, '\n'). So how would I get the copied text as a string, then how would I set the copied text with a new string.

Line :

tktextwid.event_generate('<<Paste>>')
like image 892
rectangletangle Avatar asked Oct 28 '25 10:10

rectangletangle


1 Answers

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 tk
from Tkinter import TclError

class 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

like image 95
Bryan Oakley Avatar answered Oct 31 '25 00:10

Bryan Oakley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!