简体   繁体   English

粘贴在Tkinter文本小部件中

[英]Pasting in the Tkinter Text widget

I'm using the line below to paste text in a Tkinter Text widget. 我正在使用下面的行将文本粘贴到Tkinter Text小部件中。 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'). 我专门在尝试删除所有可能导致换行的内容(例如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. 如果要预处理数据,则无需使用event_generate 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 按钮,将所有换行符转换为文字序列后,它将用剪贴板上的内容替换所选文本\\n

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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