Tkinter Text Select text
Text object get( ) method can get the currently selected text, in the use of Text text area, if there is a selected text operation occurs, the Text object will be the selected text start index in SEL_FIRST, end index in SEL_LAST, SEL_FIRST and SEL_LAST as parameters of get( ), you can get the currently selected text.
Example#1
When you click the Print selection button, you can list the currently selected text in the Python Shell window.
from tkinter import *
def selectedText():
try:
selText = text.get(SEL_FIRST,SEL_LAST)
print("Select text:",selText)
# print("SEL_FIRST:",type(SEL_FIRST)," SEL_LAST:",SEL_LAST)
except TclError:
print("No text selected")
root = Tk()
root.title("apidemos.com")
root.geometry("300x180")
# create Button
btn = Button(root,text="Print selection",command=selectedText)
btn.pack(pady=3)
# create Text
text = Text(root)
text.pack(fill=BOTH,expand=True,padx=3,pady=2)
text.insert(END,"Love You Like A Love Song") # Insert text
root.mainloop()
Output:
In the above lines 4 to 9 of the selectedText( ) method, use try…except, if there is selected text, will list the selected text.
If there is no selected text on the Print selection button will cause an exception when executing the get( ) method in line 6, which will generate a TclError exception, and then listed in the Python Shell window "No text selected".