Search code examples
python-3.xtkintertext

Tkinter - How to track the mouse cursor in a Text widget?


in my software, I always need to know where the mouse cursor is placed in a text widget. My goal is to replicate the behaviour that we can see in the classic notepad in Windows, where the lines and the colums, that identify where the cursor is placed, are always written in the status bar (see my GIF attached):

enter image description here

below a piece of my code. I already know how to take the cursor info, but how can I track where the cursor is placed in order to activate my custom function? keep in mind that the cursor can change its position using the keyboard (via arrows buttons or left mouse button)

self.T1.bind("???", self.CursorInfo)

def CursorInfo(self, *args):
    info=self.T1.index(tk.INSERT)
    print(info)

Solution

  • There is no event that fires when the text widget cursor changes. A really simple solution is to have a function run a few times a second to display the information. It will lag ever so slightly, but it will be nearly invisible to the user.

    In the following solution, update_pos will get the current index, update the label, and then schedule itself to run again in 200ms.

    import tkinter as tk
    
    root = tk.Tk()
    footer = tk.Frame(root, bd=2, relief="groove")
    text = tk.Text(root)
    footer.pack(side="bottom", fill="x")
    text.pack(fill="both", expand=True)
    
    pos_label = tk.Label(footer, width=15, anchor="w")
    pos_label.pack(side="left", fill="y")
    
    def update_pos(text):
        line, col = text.index("insert").split(".")
        pos_label.configure(text=f"Ln {line}, Col {int(col)+1}")
        text.after(200, update_pos, text)
    
    update_pos(text)
    root.mainloop()