Home > Back-end >  tkinter - How to automatically add slashes in Entry?
tkinter - How to automatically add slashes in Entry?

Time:11-13

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()

CodePudding user response:

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
  • Related