我使用了一个带有Tkinter
的文本小部件,当按下按钮时,它会将所选文本复制到剪贴板。现在在复制过程之后我想取消选择文本。
知道这可能有用吗?
由于似乎有必要发布一些代码,让人们更详细地了解我的问题,这里是:
def copy_to_clipboard(self, copy_string):
#copy to clipboard function
self.clipboard_clear()
try:
#text in outputlistfield marked, so copy that
self.clipboard_append(self.outputlistfield.get("sel.first", "sel.last"))
except:
#no text marked
outputlistfield
是一个文本小部件。如果选择了文本,则应将其复制到剪贴板。这很好。但是我想重置选择,以便在复制文本后不再选择文本。那么,有什么建议吗?
答案 0 :(得分:2)
self.outputlistfield.tag_remove(SEL, "1.0", END)
可以解决问题。如下例所示:
from tkinter import ttk
from tkinter import *
class Main(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
self.title("Test")
self.text = Text(self)
self.text.insert(END, "This is long long text, suitable for selection and copy.")
self.text.pack(expand=True, fill=BOTH)
self.frame = ttk.Frame(self)
self.frame.pack(expand=True, fill=BOTH)
self.button1 = ttk.Button(self.frame, text="Copy", command=self.OnCopy)
self.button1.pack(expand=True, fill=BOTH)
self.button2 = ttk.Button(self.frame, text="Copy & Unselect", command=self.OnCopyDeselect)
self.button2.pack(expand=True, fill=BOTH)
def OnCopy(self):
try:
text = self.text.selection_get()
except TclError:
print("Select something")
else:
self.clipboard_clear()
self.clipboard_append(text)
self.text.focus()
def OnCopyDeselect(self):
self.OnCopy()
self.text.tag_remove(SEL, "1.0", END)
root = Main()
root.mainloop()
答案 1 :(得分:0)
最简单的最简单解决方案是在附加到剪贴板后立即使用{text widget} .tag_remove(Tkinter.SEL,'1.0',Tkinter.END)从整个文本小部件中删除“SEL”标记。修改后的代码(带有一个#NEW LINE,特定于您的代码)如下:
def copy_to_clipboard(self, copy_string):
#copy to clipboard function
self.clipboard_clear()
try:
#text in outputlistfield marked, so copy that
self.clipboard_append(self.outputlistfield.get("sel.first", "sel.last"))
self.outputlistfield.tag_remove("sel", "sel.first", "sel.last") #NEW LINE
except:
#no text marked