Get the cursor position on a tkinter Text widget

0

I would like to know how to get cursor coordinates on a Text object in tkinter. For example, suppose I have this text:

  

Hello, how are you?

     

It's okay. [CURSOR]

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

    
asked by anonymous 11.12.2014 / 03:16

1 answer

0

This can be achieved using the index() method of the tkinter.Text object with the 'current' option. The following is a simple example that shows how to get either the line that 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 effbot.org , maintained by the tkinter creator, the 'current' option does the following: / p>

  

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).

    
19.01.2015 / 23:38