Jacksgrin
Jacksgrin

Reputation: 85

Tkinter Entry Multiple Vaildations

I'm trying to validations both on key and focusout such that entry is restricted to allowable characters and I can call a function when the user focuses out (leaving valid entry).

Is something like this possible?

import tkinter as tk


class Example(tk.Frame):

def __init__(self, parent):
    tk.Frame.__init__(self, parent)

    vcmd = (self.register(self.on_validate), '%S')
    vcmd2 = (self.register(self.if_valid), '%s')

    # This is the meat of the question; looking to do something like
    self.entry = tk.Entry(self, 
                          validate="key", 
                          validate2="focusout",
                          validatecommand=vcmd, 
                          validate2command=vcmd2)

    self.text = tk.Text(self, height=10, width=40)
    self.entry.pack(side="top", fill="x")
    self.text.pack(side="bottom", fill="both", expand=True)

    def on_validate(self, S):

        # Disallow anything but binary string
        if S == '1' or '0':
            return True
        else:
            self.bell()
            return False

      def if_valid(self, s):
          if len(s) == 3:
             self.my_function(s)
             return True
          else:
             return False

     def my_function(self, value):
        # send value somewhere
        pass

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

Upvotes: 1

Views: 622

Answers (1)

Peter
Peter

Reputation: 898

Taken from :https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/entry-validation.html Perhaps you want to use all?

'focus' Validate whenever the Entry widget gets or loses focus (see Section 53, “Focus: routing keyboard input”).

'focusin' Validate whenever the widget gets focus.

'focusout' Validate whenever the widget loses focus.

'key' Validate whenever any keystroke changes the widget's contents.

'all' Validate in all the above situations.

'none' Turn off validation. This is the default option value. Note that this is the string 'none', not the special Python value None.

If it was essential that you only validate focusout and key, then you could use all and then in your validation method you could simply call the .get_focus() method to see if the focus was on the box or not.

Upvotes: 2

Related Questions