Home > Software engineering >  Auto Bracket Closing in Tkinter
Auto Bracket Closing in Tkinter

Time:07-26

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!

CodePudding user response:

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()
  • Related