2011-08-04 65 views
1

我正在使用下面這行來粘貼Tkinter文本部件中的文本。但是,我希望能夠在粘貼之前更改文本。我特意試圖刪除任何會導致創建新行的東西(例如,返回'\ n')。那麼,如何將複製的文本作爲字符串獲取,然後如何使用新字符串設置複製的文本。在Tkinter文本部件中粘貼

線:

tktextwid.event_generate('<<Paste>>') 

回答

4

你並不需要使用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