I have used a Text widget with Tkinter
that copies selected text to the clipboard when a button is pressed. Now after the copy process I would like to unselect the text.
Any idea how that might work?
Since it seems to be necessary to post some code, for people to understand my problem in more detail, here it is:
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
is a Text widget. If Text is selected, it shall be copied to clipboard. That works fine. But I would like to reset the selection, so that after the text is copied no text is selected anymore. So, any suggestions?
In Tkinter, sometimes, we may want to make a text widget disabled. To achieve this, we can set the text configuration as DISABLED. This will freeze the text widget and will make it read-only.
Type something inside the textbox, and then, click the “Delete” button. It will erase the content inside the textbox.
In this tutorial we will discuss the Python Tkinter Config function, which is used to configure certain options in widgets. When you create a widget in Tkinter, you have to pass in several values as parameters, used to configure certain features for that Widget.
The Entry widget is used to accept single-line text strings from a user. If you want to display multiple lines of text that can be edited, then you should use the Text widget.
self.outputlistfield.tag_remove(SEL, "1.0", END)
would do the trick. As in this example:
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With