NurseStacey
NurseStacey

Reputation: 3

Trouble with change text in tk.Entry on validation

I want to create an entry field for a date. I want the user to be able to type the digits for the month, day, year and have the '/' come up automatically. I thought I would be able to do this with validation and here's my code:

def __init__(self, *args, **kwargs)
     super().__init__(*args,**kwargs)
     self.grid_propagate(False)

     reg = self.register(self.validate_date)
     tk.Entry(self,name='the_entry', validate="key", validatecommand=(reg, '%P')).grid(row=0, column=1,sticky='E')

def validate_date(self,input):
    
    if input=='':
        return True
    
    if not input[-1].isdigit():
        return False
    
    if len(input)==10:
        return False
    
    if len(input) in [2,5]:
        
        self.nametowidget('the_entry').delete(0,tk.END)
        self.nametowidget('the_entry').insert(0,input + '/')
        

    return True

But what happens is I get one '/' and after that it stops calling the validation function. I've tried re-assigning the validation function with the following code in the if statement:

        self.nametowidget('the_entry').config(validate="key")
        self.nametowidget('the_entry').config(validatecommand= 
(self.register(self.validate_date), '%P'))

When I do that it no longer is adding the '/'.

Can anyone recommend a better way to get the behavior I'm looking for?

Upvotes: 0

Views: 67

Answers (0)

Related Questions