-2
I adapted the program from here and worked well.
Note 1 Imagining this CPF 11.111.111-11 - The same would have to be entered as 011.111.111-11
Note 2 ENTER must be given for the field to be "read"
from __future__ import print_function
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
class CpfEntry(tk.Frame):
def __init__(self, master, frame_look={}, **look):
args = dict(relief=tk.SUNKEN, border=1)
args.update(frame_look)
tk.Frame.__init__(self, master, **args)
args = {'relief': tk.FLAT}
args.update(look)
self.entry_1 = tk.Entry(self, width=3, **args)
self.label_1 = tk.Label(self, text='.', **args)
self.entry_2 = tk.Entry(self, width=3, **args)
self.label_2 = tk.Label(self, text='.', **args)
self.entry_3 = tk.Entry(self, width=3, **args)
self.label_3 = tk.Label(self, text='-', **args)
self.entry_4 = tk.Entry(self, width=2, **args)
self.entry_1.pack(side=tk.LEFT)
self.label_1.pack(side=tk.LEFT)
self.entry_2.pack(side=tk.LEFT)
self.label_2.pack(side=tk.LEFT)
self.entry_3.pack(side=tk.LEFT)
self.label_3.pack(side=tk.LEFT)
self.entry_4.pack(side=tk.LEFT)
self.entries = [self.entry_1, self.entry_2, self.entry_3, self.entry_4]
self.entry_1.bind('<KeyRelease>', lambda e: self._check(0, 3))
self.entry_2.bind('<KeyRelease>', lambda e: self._check(1, 3))
self.entry_3.bind('<KeyRelease>', lambda e: self._check(2, 3))
self.entry_4.bind('<KeyRelease>', lambda e: self._check(3, 2))
def _backspace(self, entry):
cont = entry.get()
entry.delete(0, tk.END)
entry.insert(0, cont[:-1])
def _check(self, index, size):
entry = self.entries[index]
next_index = index + 1
next_entry = self.entries[next_index] if next_index < len(self.entries) else None
data = entry.get()
if len(data) > size or not data.isdigit():
self._backspace(entry)
if len(data) >= size and next_entry:
next_entry.focus()
def get(self):
return [e.get() for e in self.entries]
if __name__ == '__main__':
win = tk.Tk()
win.title('CPF - demo')
cpf_entry = CpfEntry(win, font=('Arial', 40, tk.NORMAL), border=0)
cpf_entry.pack()
win.bind('<Return>', lambda e: print(cpf_entry.get()))
win.mainloop()
I hope it helps