[英]Pasting in the Tkinter Text widget
我正在使用下面的行将文本粘贴到Tkinter Text小部件中。 但是,我希望能够在粘贴之前更改文本。 我专门在尝试删除所有可能导致换行的内容(例如return,'\\ n')。 因此,如何将复制的文本作为字符串,然后如何使用新的字符串设置复制的文本。
线:
tktextwid.event_generate('<<Paste>>')
如果要预处理数据,则无需使用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()
当您运行此代码并单击“执行!”时 按钮,将所有换行符转换为文字序列后,它将用剪贴板上的内容替换所选文本\\n
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.