'Tkinter events lag behind cursor position

I am in the process of writing a simple GUI text editor using tkinter and python, and while implementing a line and column number readout, I noticed that when I set the update of the readout to a mouse or keyboard event, the column readout always seems to lag 1 event behind what has actually occurred.

The code in question is as follows:

def update_line_num(event):
  line_num, col_num = txt_field.text.index("insert").split('.') # Get the line and column numbers
  status_line_txt.configure(text=f"ln {line_num} : col {col_num}") # Update the UI

  statusbar.draw() # Update the statusbar and it's children.

I then bind this function with the tk.Text.bind("<Event>", function) syntax. In this case, I am binding to the Button and KeyPress events.

However, this results in a column readout which lags behind the true cursor position by 1 event. By this, I mean that when I press a key or click the mouse to a different piece of text, the column readout always displays the location the cursor was just at.

I know its not an issue with the update code for the actual UI, because when I print the line and column numbers out, I get the same incorrect numbers.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source