[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[tkinter] question about correct use of validation

for determine the maximum number of characters in an entry

I have read several interpretations for the solution of the problem, but 
I wanted to find an alternative way (for convenience of the code)

I kindly ask for an opinion on the use of validation in this way.


problem: limit number of characters in different entries of a form.


# -*- coding: utf-8 -*

from Tkinter import *

class View():

     def __init__(self, parent):
         self.parent = parent

     def make_ui(self):
         ''' create user interface '''
         self.id_entry = Entry(self.parent, width=6)
         # take out the properties for understanding

         vcmd = (self.parent.register(self.maxlength_validate), '%P', 4)
	# 4 is my question

         self.id_entry.configure(validate="key", validatecommand=vcmd)

         self.name_entry = Entry(self.parent, width=30)
         # take out the properties for understanding

         vcmd = (self.parent.register(self.maxlength_validate), '%P', 20)
	# 20 is my question

         self.name_entry.configure(validate="key", validatecommand=vcmd)

     def maxlength_validate(self, value, maxlength):
         ''' function validated for maximum number of characters '''
         maxlength = int(maxlength)
         if len(value) > maxlength:
             value = value[:maxlength]
             return (value == ' ')
         return True

def run():
     root = Tk()

if __name__ == "__main__":

The code works well :-) but...

in vcmd i use this:

vcmd = (self.parent.register(self.maxlength_validate), '%P', 20)
# '20' argument is my question, is not default value (is max length of 
char, different for each entry... very comfortable for me)

is it all right, according to you, to pass a non-default argument? (no 
error from the interpreter)

Without this way I would not know how to pass the maximum number of 
characters to the validation function, I can not use one variable
self.--- for each entry ... it would become aesthetically unattractive.

I would not even like to add a textvariable variable because anyway then

I should always pass the comparison value.

thank you in advance