Как в Tkinter узнать позицию курсора и выделенный текст в виджете Entry?
Как в Tkinter узнать позицию курсора и выделенный текст в виджете Entry?
Ответы (1 шт):
Есть текстовые индексы Entry, соответствующие, например, позиции курсора и начала/конца выделения:
INDICES
Many of the widget commands for entries take one or more indices as arguments. An index specifies a particular character in the entry's string, in any of the following ways:
number- Specifies the character as a numerical index, where 0 corresponds to the first character in the string.
"anchor"- Indicates the anchor point for the selection, which is set with theselect_from()andselect_adjust()widget methods.
"end"- Indicates the character just after the last one in the entry's string. This is equivalent to specifying a numerical index equal to the length of the entry's string.
"insert"- Indicates the character adjacent to and immediately following the insertion cursor.
"sel.first"- Indicates the first character in the selection. It is an error to use this form if the selection is not in the entry window.
"sel.last"- Indicates the character just after the last one in the selection. It is an error to use this form if the selection is not in the entry window.
@number- In this form, number is treated as an x-coordinate in the entry's window; the character spanning that x-coordinate is used. For example,"@0"indicates the left-most character in the window.
По информации отсюда: tkinter.Entry
Эти индексы можно использовать в некоторых методах Entry, вот пример для вставки текста в позиции курсора: entry.insert("insert", "Some text").
Для получения числовых значений этих индексов можно использовать метод .index().
Полный пример с выводом позиции курсора, начала/конца выделения и выделенного текста:
from tkinter import *
root = Tk()
entry = Entry()
entry.pack()
def command():
print("Cursor positon:", entry.index("insert"))
if entry.selection_present():
selection_from = entry.index("sel.first")
selection_to = entry.index("sel.last")
print(f"Selection from {selection_from} to {selection_to}")
print("Selected text:", entry.get()[selection_from:selection_to])
button = Button(text="Press me", command=command)
button.pack()
root.mainloop()