Python Forum

Full Version: text get index problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I made a small example of my problem:
from tkinter import *

root = Tk()

text = Text(root)
text.pack()

text.insert('insert', 'some text')

def print_cursor_index(evt):
    try: print(text.count('1.0','insert')[0])
    except: print(0)

text.bind('<1>',print_cursor_index)

root.mainloop()
The goal is to make a mouseclick on the text widget return the cursor index position on the text. I found out I can change text.bind to root.bind and it will work as expected but in this case I want the click-bind only on the text widget(in my more complex GUI). The problem is that in the current code returns the wrong index from one click ago. Please try it yourself. I want to understand why and wanna know if there is a way to solve the problem. Keep in mind that the bind needs to be text.bind('<1>',print_cursor_index)

the problem only occurs when binding a mouse button.
You need to bind on the release of button 1
text.bind('<ButtonRelease-1>',print_cursor_index)
(Feb-02-2022, 07:46 PM)Yoriz Wrote: [ -> ]You need to bind on the release of button 1
text.bind('<ButtonRelease-1>',print_cursor_index)
Thank you that worked!