0

In my project I'm trying to add matching parentheses as I type into a tkinter.Text widget. Basically, when I type (, the program automatically inserts ).

The only answer I could find for this same issue is here. I tried all three options the selected answer had, and none worked. The answer is 10 years old so I thought it would have been outdated.

Here is what I have so far. The code works, but the ending-parentheses is inserted before the start-parentheses. (looks like this )(.). How can I make the ending-parentheses get inserted after the starting one?:

text_box.bind("<(>", lambda n: text_box.insert(float(text_box.index("insert")) + 1, ")"))

It would also help if the ending-parentheses is put after the cursor (to the left of your cursor is ( and to the right is )

Thanks for any answers

Expliked
  • 101
  • 10
  • _"The answer is 10 years old so I thought it would have been outdated."_ - no, the answer isn't outdated. This behavior is fundamental to how to works, and hasn't changed in decades. – Bryan Oakley Feb 06 '21 at 14:49

1 Answers1

1

You should insert the closing ) at the insertion position and then move the insertion cursor back 1 character:

def close_parenthese(event):
    logbox.insert("insert", ")") # add the closing )
    logbox.mark_set("insert", "insert-1c") # move back the insertion cursor

text_box.bind("(", close_parenthese)
acw1668
  • 40,144
  • 5
  • 22
  • 34
  • This technically works, but I still need to find a working way to make binds execute after the text is entered :( – Expliked Feb 06 '21 at 23:40