如何从Python Tkinter Text widget获取所选文本的开始和结束位置

问题描述 投票:0回答:1

我想获取 Tkinter 文本小部件中所选文本的开始和结束位置。如果没有选择文本,则应使用光标的位置作为开始和结束位置。

如果选择从“1.0”开始,它还会返回错误。

我有有效的代码,但我想知道是否有更简单的方法来做同样的事情:

from tkinter import *

# Objective:
# Get position of start and end of selection in a tkinter text widget
# Use SEL_FIRST and SEL_LAST
# If no text are selected, SEL_FIRST and SEL_LAST will return an error
# Also, if the selection starts at "1.0" SEL_FIRST will return an error

# Generate text
testText = ""
for r in range(8):
    testText += f'{r+1}12345678\n'

def get_info_of_selection():
   
    # Boolean variables for selection
    no_selection = False    # If True --> no text is selected
    start_found = False     # If True --> start of selection was found

    # CURSOR: determine index and position
    index_cursor = myTextWidget.index(INSERT)   # Can also use "insert"
    if index_cursor == "1.0":
        position_cursor = 0
        # If the cursur is at the beginning, the start of the selection will also be there
        start_found = True
        index_start = index_cursor
        position_start = position_cursor
    else:
        position_cursor = myTextWidget.count("1.0", index_cursor)[0]

    # END OF SELECTION: Determine index and position
    try:
        index_end = myTextWidget.index(SEL_LAST)   # Can also use "sel.last" instead of "SEL_LAST"
        position_end = myTextWidget.count("1.0", SEL_LAST)[0]
    except:
        # No text is selected --> use the index and position of the cursor
        index_end = index_cursor
        position_end = position_cursor
        # Also, set no_selection to True
        no_selection = True

    # START OF SELECTION: determine index and position
    if not start_found:
        if no_selection:
            # If no text is selected --> use the index and position of the cursor
            index_start = index_cursor
            position_start = position_cursor
        else:
            try:
                index_start = myTextWidget.index(SEL_FIRST)   # Can also use "sel.first" instead of "SEL_FIRST"
                position_start = myTextWidget.count("1.0", SEL_FIRST)[0]
            except:
                index_start = "1.0"
                position_start = 0

    # Update label with information
    msg = f'Cursor index | position = {index_cursor} | {position_cursor}\nStart index | position = {index_start} | {position_start}\nEnd index | position = {index_end} | {position_end}'
    myLabel.config(text = msg)
    


root = Tk()

myButton = Button(root, text="Get start and end position of selection/cursor", command=get_info_of_selection)
myButton.pack(pady=10, ipady=5)

myTextWidget = Text(root)
myTextWidget.pack(fill=X)
myTextWidget.insert('insert', testText)

myLabel = Label(root, text="")
myLabel.pack()

root.mainloop()

tkinter position cursor selection
1个回答
0
投票

你把问题变得过于复杂了。您可以使用索引

"sel.first"
"sel.last"
获取选择的开始和结束索引。您可以在 try/ except 块中使用它们,这样如果没有选择,您可以将值设置为
"insert"
:

的索引
def get_info_of_selection():
    try:
        index_start = myTextWidget.index("sel.first")
        index_end = myTextWidget.index("sel.last")
    except TclError:
        index_start = index_end = myTextWidget.index("insert")

    msg = f"start: {index_start}\nend: {index_end}"
    myLabel.config(text = msg)
© www.soinside.com 2019 - 2024. All rights reserved.