O'Reilly logo

Tkinter GUI Programming by Example by David Love

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Getting the cursor's position

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

import tkinter as tkwin = 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required