Getting the Cursor position in Tkinter Entry widget


We are already familiar with input forms where various single Entry fields are created to capture the user input. With Tkinter, we can also create a single input field using the Entry widget. Each character in the Entry field that the user enters is indexed. Thus, you can retrieve this index to get the current position of the cursor by using the index() method. To retrieve the current location of the cursor, you can pass the INSERT argument in this function.


# Import required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter window
win = Tk()
win.title("Get the Cursor Position")

# Create an instance of style class

# Function to retrieve the current position of the cursor
def get_current_info():
   print ("The cursor is at: ", entry.index(INSERT))

# Create an entry widget
entry=ttk.Entry(win, width=18)

# Create a button widget
button=ttk.Button(win, text="Get Info", command=get_current_info)



Running the above code will display a window with an Entry widget and a button which can be used to get the current index of the cursor.

Type some text in the Entry widget and click the "Get Info" button. It will print the current location of the cursor on the console.

The cursor is at: 15
Published on 22-Dec-2021 10:46:22