Tkinter Auto-update button state

I'm building a very basic login system. I've almost completed it but I have one problem. I need to put a check in the 'register' button to be disabled untill it's entry meets some conditions. Something like this. Now, I'm aware that 'while loops' don't work in tkinter and why. This is just an example of what I'm trying to do! Any advice?


What you can do is create the register button, but set the state to disabled;

regbtn = ttk.Button(
    root, text="Register",
    command=do_register,
    state=tk.DISABLED
)

Later, you can treat regbtn like a dictionary and modify the state:

regbtn["state"] = "enabled"

To know when to enable the button, you need to validate the entry field. (For example, my resin-calculator program does input validation.)

But it short, it involves:

  1. registering a validation function with the tk.TK object.
  2. Setting the Entry widget to validate on a keypress.

For example, say we want to validate that an entry is a number. To do that we create a function as shown below. As a side-effect, this validation function enables/disables the register button depending on the validity of the data:

def is_number(data):
    """Validate the contents of an entry widget as a float."""
    try:
        float(data)
    except ValueError:
        regbtn["state"] = "disabled"
        return False
    regbtn["state"] = "enabled"
    return True

This function receives the contents of the entry widget and needs to return if that data is valid.

So, first we register that validation command;

    root = tk.TK()
    vcmd = root.register(is_number)

Then, when creating the button, we set it to call the validation whenever a key is pressed;

re = ttk.Entry(
    parent,
    validate="key",
    validatecommand=(vcmd, "%P")
)