1

I have been trying to integrate some validation to a text entry field.

I found a VERY useful post here, by user unbutu, which creates a text entry field that can only accept the characters: `0123456789.+-]. I then attempted to deconstruct the code example, in order to better understand how it worked.

My reduced code is below, but there are several parts I am still puzzled by. If anyone can lend their wisdom to help me understand, I'd be really grateful.

import tkinter as tk


# Create root window
root = tk.Tk()


class entryWithValidation:
    def __init__(self, parent):

        # Calls the validationFunc function? Why no parenthesis? How do arguments get
        # passed to the function?
        checkFunc = self.validationFunc

        # note 1
        registeredCheckFunc = parent.register(checkFunc)

        # As far as I can tell, this is just a tuple to improve readability.
        # The whole tuple needs to be passed as a single argument to 'validatecommand' 
        shortcut = (registeredCheckFunc,'%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')

        # creates an entry widget, within 'root', that runs the validation command
        # whenever a key is pressed. The validation command is 'shortcut'
        self.textEntry = tk.Entry(root,
                              validate = 'key',
                              validatecommand = shortcut)

        # Packs entry like normal
        self.textEntry.pack()


    # What are all the arguments for? They don't seem to get used anywhere
    def validationFunc(self, action, index, value_if_allowed,
                 prior_value, text, validation_type,
                 trigger_type, widget_name):

        # However the 'text' argument is passed to this function,
        # it checks the character against the string of valid characters provided,
        # and returns true if present, false if not.
        if text in '0123456789':
            return True
        else:
            return False

entryWithValidation(root)

root.mainloop()

Note 1: I've read the documentation at effbot, but to be honest I can't make heads or tails of it. Tcl wrapper procedure? Python callback? What?

0 Answers0