0

When I enter a date in an Entry I would like for it to have slashes between dates like so:
"01/23/4567".

I found this code and although it works while also validating that the entry are numbers, there is one problem. It doesn't let me clear the entry input. I tried the .delete(0, END) method with a button but doesn't seem to work at all and if you press backspace, the first character, "0" in this example "01/23/4567", doesn't get deleted, it stays there.

import tkinter as tk, re

class DateEntry(tk.Entry):
    def __init__(self, master, **kwargs):
        tk.Entry.__init__(self, master, **kwargs)
        vcmd = self.register(self.validate)
        
        self.bind('<Key>', self.format)
        self.configure(validate="all", validatecommand=(vcmd, '%P'))
        
        self.valid = re.compile('^\d{0,2}(\\\\\d{0,2}(\\\\\d{0,4})?)?$', re.I)
             
    def validate(self, text):
        if ''.join(text.split('\\')).isnumeric():
            return not self.valid.match(text) is None
        return False
    
    def format(self, event):
        if event.keysym != 'BackSpace':
            i = self.index('insert')
            if i in [2, 5]:
                if self.get()[i:i+1] != '\\':
                    self.insert(i, '\\')
        

class Main(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        
        DateEntry(self, width=10).grid(row=0, column=0)
        

if __name__ == "__main__":
    root = Main()
    root.geometry('800x600')
    root.title("Date Entry Example")
    root.mainloop()
martineau
  • 119,623
  • 25
  • 170
  • 301
Nikos
  • 3
  • 2
  • 1
    You are inserting backslashes, not forward slashes. Dates use forward slashes. – Tim Roberts Nov 12 '21 at 19:02
  • I don't see your `delete` call here. – Tim Roberts Nov 12 '21 at 19:02
  • Thanks for your time Tim, i haven't included my delete call since i couldn't make it work, just the code that works (which is not mine) hopping that someone can point me to the right direction. – Nikos Nov 12 '21 at 19:07
  • Does this answer your question? [Auto add dashes to entryboxes in tkinter](https://stackoverflow.com/questions/62119551/auto-add-dashes-to-entryboxes-in-tkinter) – Delrius Euphoria Nov 12 '21 at 20:43
  • 1
    @CoolCloud That helped me change the backward slashes to forward. Thanks! – Nikos Nov 13 '21 at 00:57

1 Answers1

0

If you need to be able to clear the widget, your validation function needs to account for the special case of an empty value.

def validate(self, text):
    if text.strip() == "":
        # allow a completely empty entry widget
        return True
    if text ''.join(text.split('\\')).isnumeric():
        return not self.valid.match(text) is None
    return False
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685