Search code examples
pythonfunctiontkintertkinter-entry

Keybind causes function to run automatically on startup


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.


Solution

  • 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 _: