粘贴到 Tkinter 文本小部件中

rec*_*gle 3 python string text copy-paste tkinter

我正在使用下面的行将文本粘贴到 Tkinter 文本小部件中。但是,我希望能够在粘贴文本之前对其进行更改。我特别想删除任何会导致创建新行的内容(例如,返回,'\n')。那么我如何将复制的文本作为字符串获取,然后我将如何使用新字符串设置复制的文本。

线 :

tktextwid.event_generate('<<Paste>>')
Run Code Online (Sandbox Code Playgroud)

Bry*_*ley 5

event_generate如果要预处理数据,则不需要使用。您只需要抓取剪贴板内容,操作数据,然后将其插入到小部件中。要完全模仿粘贴,您还需要删除选择(如果有)。

这是一个简单的例子,几乎没有测试:

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()
Run Code Online (Sandbox Code Playgroud)

当您运行此代码并单击“do it!”时。按钮,它将在将所有换行符转换为文字序列后用剪贴板上的内容替换所选文本\n