简体   繁体   中英

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 (eg, 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>>')

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM