簡體   English   中英

粘貼在Tkinter文本小部件中

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM