Getting the cursor's position

Open up a new Python file and enter the following code:

import tkinter as tk

win = tk.Tk()
current_index = tk.StringVar()
text = tk.Text(win, bg="white", fg="black")
lab = tk.Label(win, textvar=current_index)

Begin with the normal importing and creation of a main window.

The things we will need for this application are a StringVar to hold the current cursor location, a Text widget to navigate around, and a Label to display our StringVar.

Now we need a function to hook to the <KeyRelease> event which will update our StringVar with the current cursor coordinates:

def update_index(event=None):
cursor_position = text.index(tk.INSERT)
cursor_position_pieces = str(cursor_position).split('.')

cursor_line = cursor_position_pieces[0]
cursor_char = cursor_position_pieces[1]

current_index.set('line: ' + cursor_line + ' char: ' + cursor_char +
' index: ' + str(cursor_position))

In order to get the cursor's current position, we use the index method of the Text widget. This method will return the index of certain items which can reside within it. Since we want the location of the cursor, we use the built-in constant INSERT which refers to it.

This returns the index in the previously mentioned format of line number, full stop, and character number.

To separate these two pieces of information, we cast this to a string and use the split method to separate the two numbers from the full stop.

Each number is then stored in its own variable.

To make this information visible to the user, we create a string that contains the line number, character number, and complete index. This is then assigned to our StringVar with its set method.

Now we need to put these widgets into our main window, bind the <KeyRelease> event, and run the application:

text.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
lab.pack(side=tk.BOTTOM, fill=tk.X, expand=1)

text.bind('<KeyRelease>', update_index)

win.mainloop()

Launch this application and type away in the Text widget (or copy and paste a bit of text) and move the cursor around. You should be shown the position at the bottom, and what it means:

This covers the basics of cursor positioning. Most of the indexing you will need to do can be done like this, but there are certain tasks that will be tedious to calculate, for example, finding the last character of a line, or moving three characters forward. Luckily, Tkinter has a way of making this easy to do.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset