Get cursor position in Tkinter Text widget

Asked

Viewed 514 times

0

I wonder how I can get cursor coordinates on an object Text in Tkinter. For example, suppose I have this text:

Hello, how are you?

It’s all right. [CURSOR]

How do I get the row and column of [CURSOR]?

1 answer

0


This can be obtained using the method index() of the object tkinter.Text with the option 'current'. The following is a simple example that shows how to get the line the current character, or where the cursor is positioned:

import tkinter as tk

class FooterBar(tk.Frame):
    def __init__(self, master=None, **options):
        tk.Frame.__init__(self, master, **options)
        self.lines = tk.Label(self, text='Lines: ', relief='sunken', border=1, padx=10)
        self.lines.pack(side='left')
        self.chars = tk.Label(self, text='Chars: ', relief='sunken', border=1, padx=10)
        self.chars.pack(side='left')

    def set(self, mouse_pos):
        self.lines['text'] = 'Line: ' + mouse_pos.split('.')[0]
        self.chars['text'] = 'Charater: ' + mouse_pos.split('.')[1]

def run():    
    master = tk.Tk()
    text = tk.Text(master)
    text.pack(expand=True, fill='both')
    text.bind('<KeyRelease>', lambda e: footer.set(text.index('current')))
    # nota que estou a usar <KeyRelease>
    footer = FooterBar(master, background='#eee')
    footer.pack(fill='x')
    master.mainloop()

if __name__ == '__main__':
    run()

According to the website effbot.org, maintained by the creator of Tkinter, the option 'current' does the following:

CURRENT (or "Current") Corresponds to the Character Closest to the mouse Pointer. However, it is only updated if you move the mouse without holding down any Buttons (if you do, it will not be updated until you release the button).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.