在Tkinter Text控件中粘贴
我在使用下面这行代码把文本粘贴到Tkinter的文本框里。不过,我想在粘贴之前先修改一下文本。我特别想去掉那些会导致换行的内容,比如回车符和'\n'。那么,我该如何把复制的文本作为字符串获取,然后又该如何用新的字符串来替换这个复制的文本呢?
代码行:
tktextwid.event_generate('<<Paste>>')
1 个回答
6
如果你打算先处理数据,就不需要使用 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
。