0

i am facing a problem. I'm runnig this code.

import tkinter as tk

root = tk.Tk()
def check():
   if len(e.get().split("a")) > 1:
      print("contains a")

e = tk.Entry(frame1)
e.grid(row=4,column=1,columnspan=2,padx = (10,10), pady=(5,10), sticky="w e")
e.bind("<Key>",check)

when i type "a" to the entry I wont get nothing printed. I'll get the result by tiping a second character. I think that it happens because the function gets executed before the content has actualy changed. I tried to add a timer on the beginning of the function but it does nothing. I want get the result by entering the first "a". What should I do?

1 Answers1

1

I think that it happens because the function gets executed before the content has actualy changed.

You're right. If you want the callback to be able to see the character you just typed, you should create a StringVar and bind to that instead of binding to a "<Key>" event on the widget.

import tkinter as tk

frame1 = tk.Tk()
def check(*args):
    if "a" in s.get():
        print("contains a")

s = tk.StringVar()
e = tk.Entry(frame1, textvariable=s)
s.trace("w", check)
e.grid(row=4,column=1,columnspan=2,padx = (10,10), pady=(5,10), sticky="w e")
frame1.mainloop()
Kevin
  • 74,910
  • 12
  • 133
  • 166
  • Works fine. I didn't know about the StringVar(). One more question, how can I remove the drawing animation of the turtle module. turtle.spped(0) and turtle.speed("fastest") is not working fine for me. I want my picture get drawn instantly. Thanks – PatoKrivulcik Mar 25 '17 at 16:16