I'm trying to insert "(),"
after the a button click or a keyboard shortcut in the Text
and then move the cursor into the parentheses like this (|),
. Here is the relevant part of the code.
def addParentheses(event = None):
key_text.focus_set()
key_text.insert('current', '(),')
pos = key_text.index('current')
col = int(pos.split('.')[0])
row = int(pos.split('.')[1])
key_text.mark_set('insert', "%d.%d" % (col,row-2))
This code works as expected only if my mouse pointer hovers over the Text
widget. If my pointer is elsewhere in the Frame
, it inserts "(),"
at the beginning of the line as opposed to the end.
Any help would be appreciated.
I think there may be two problems. First, "current" refers to the location of the mouse, not the insertion cursor. It's not clear if that's what you're really intending to use or not. When the mouse is not directly over the widget, the index will refer to the last position of the mouse over the widget before it left the boundary of the widget.
The behavior should be that if you move your mouse outside of the text widget on the right, the text will be inserted at the end of the line closes to where the mouse crossed the edge. If you move your mouse outside of the text to the left, the text will get inserted at the start of the line closest to where the mouse crossed the edge.
Second, you're not calculating the line and column correctly. You are setting the column to the first part of the index and the row to the second. You have that reversed. The first part before the "." represents the line number, and the second part after the "." represents the column number.
You need to be computing the line and character like this:
pos = key_text.index('current')
line = int(pos.split('.')[0])
char = int(pos.split('.')[1])
key_text.mark_set('insert', "%d.%d" % (line,char-2))