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.geometry("700x350") win.title("Get the Cursor Position") # Create an instance of style class style=ttk.Style(win) # 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) entry.pack(pady=30) # Create a button widget button=ttk.Button(win, text="Get Info", command=get_current_info) button.pack(pady=30) win.mainloop()
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