0

I'm making a code editor and everything is good! But I want to make a feature which auto closes your bracket (testing with letter 'a'). Here is my code: (bracket close part)

st is my scolled text and self is the root window, I am testing with when you press 'a' but it inserts the bracket before the key ('a') is added into the text box.

#bracket open and close

    def bo(event):
      print("hello")
      self.st.insert(END, ")")
      
      return

    
    self.st.bind('<KeyPress-a>', bo)

Thank you! Have a good day!

petezurich
  • 9,280
  • 9
  • 43
  • 57
Chiz
  • 7
  • 2
  • This answer explains exactly what is happening: https://stackoverflow.com/questions/11541262/basic-query-regarding-bindtags-in-tkinter/11542200#11542200 – Bryan Oakley Jul 25 '22 at 14:15

1 Answers1

1

Use the KeyRelease event instead, otherwise your function call is executed before the actual letter is inserted into your Text widget.

from tkinter import Tk, Text, END

def bo(event):
    st.insert(END, ")")

root = Tk()
st = Text(root)
st.bind("<KeyRelease-a>", bo)
st.pack()
root.mainloop()
mnikley
  • 1,625
  • 1
  • 8
  • 21