To create a simple line-column counter for my text editor, I decided to simply use the index
function of the tkinter.Text
widget. In fact, the index
function returns a string representing the line and column of the coordinates passed as argument to it.
Specifically, I am using cursor_pos = text.index(tkinter.INSERT)
to get the index of the cursor, since, from the effbot website on tkinter.INSERT
:
tkinter.INSERT corresponds to the insertion cursor.
The problem is that tkinter.INSERT
seems to give me the last cursor position until I move the cursor with the arrows (for example).
This is the function that handles the count of the lines and columns:
def on_key_pressed(self, event=None):
"""Docs """
if self.tpane is not None:
print(self.lines, self.columns)
self.tpane.update()
cursor_pos = self.tpane._tabs[self.tpane.selected()].text.index(tkinter.INSERT)
self.lines = int(cursor_pos.split('.')[0])
self.columns = int(cursor_pos.split('.')[1])
print(self.lines, self.columns)
self.line_c.config(text='Lines: ' + str(self.lines))
self.col_c.config(text='Columns: ' + str(self.columns))
self.update()
I don't know if you can understand the situation... When I first type a letter on the editor, the self.columns
variable does not update to 1 (remains 0) until I write the second letter, where it updates to 1, and so on. But there's a trick to make it update without writing a new letter. Once written the first letter, if I move the cursor with the arrows, it updates the self.columns
to actually 1.
Another problem is when I try to delete a existent character. For example, if I have 3 characters (and suppose I have self.columns
to 3), and I press delete
, self.columns
update inexplicably to 4
, and if I try to remove another character, at this point, it updates to 3.
This problems exists also for the self.lines
in the on_key_pressed
event handler. I am not sure if this is supposed to happen, and if yes, then I am missing something...