1

I am trying to create a keybind for my Entry, which takes what the user has inputted into the Entry and then calls a function.

My code:

def nameValidation(name):
    if PresenceCheck(name) and LengthCheck(name,2) and DataTypeCheck(name,str):
        print("Valid Name")
    else:
        nameEntry.configure(bg="red")
nameEntry = tk.Entry(root,textvariable=nameInput,bg="white",font=("Arial",28))
nameEntry.grid(row=2,column=2)
nameEntry.bind("<FocusOut>",nameValidation(nameInput.get()))

When I run the code, the Entry is coloured red, indicating the function has been called, even though the keybind was not activated.

10 Rep
  • 2,217
  • 7
  • 19
  • 33
Lyra Orwell
  • 1,048
  • 4
  • 17
  • 46

1 Answers1

2

You are making a very common mistake. Your function is executing on the execution of your program, because you have called it with parentheses in your .bind().

A way to fix this would be to add a lambda.

Code:

def nameValidation(name, event = None):
    if PresenceCheck(name) and LengthCheck(name,2) and DataTypeCheck(name,str):
        print("Valid Name")
    else:
        nameEntry.configure(bg="red")
nameEntry = tk.Entry(root,textvariable=nameInput,bg="white",font=("Arial",28))
nameEntry.grid(row=2,column=2)
nameEntry.bind("<FocusOut>", lambda: nameValidation(nameInput.get()))

Hope this helps!


As stated in the comments, use lambda: event if you want the anonymous function. If you get an error with that, use lambda _:

10 Rep
  • 2,217
  • 7
  • 19
  • 33
  • 2
    This will throw an error all the binds pass an event argument to the first parameter of the callback function. – Saad Jun 27 '20 at 14:45
  • @Saad Thanks for pointing out that error. I will edit my answer. – 10 Rep Jun 27 '20 at 14:46
  • 1
    Here the callback function is the anonymous function lambda not `nameValidation`, it should be `lambda event: ... ` – Saad Jun 27 '20 at 14:49
  • @Saad I get this error with your solution in the line def nameValidation(event = None, name): SyntaxError: non-default argument follows default argument – Lyra Orwell Jun 27 '20 at 14:50
  • 2
    or just `lambda _: ...` if you're not using the argument – michalwa Jun 27 '20 at 14:50
  • 1
    Also, `nameValidation(event = None, name)` this will give an error. You can't give a default parameter before a normal parameter – Saad Jun 27 '20 at 14:53
  • @Saad I am sorry! I think I am sleepy, let me edit my answer. – 10 Rep Jun 27 '20 at 14:54