Tkinter: Formatting Data as a user types it Tkinter: Formatting Data as a user types it tkinter tkinter

Tkinter: Formatting Data as a user types it


Instead of inserting in the dashes on-the-fly, and suffering from desynchronization issues, a better solution would be to always start with a clean copy of the numbers, without any dashes, and then add them afterwards. That way, no matter how many modifications are made, you will always add the dashes in the right spaces.

An example:

from Tkinter import *class App:    def __init__(self, master):        self.label = Label(text="ID#: ")        self.currentData = StringVar()        self.entry = Entry(textvariable=self.currentData)        self.positions = [3, 6]        self.label.grid(row=0, column=0)        self.entry.grid(row=0, column=1)        self.entry.focus_set()        root.bind('<Key>', self.formatData)    def formatData(self, master):        # Adding dashes        raw = [char for char in self.currentData.get() if char != '-']        for index in self.positions:            if len(raw) > index:                raw.insert(index, '-')        self.currentData.set(''.join(raw))        # Prevent cursor from derping        cursor = self.entry.index(INSERT)   # Gets the current cursor position        for index in self.positions:            if cursor == (index + 1):                                # Increment the cursor if it falls on a dash                cursor += 1        if master.keysym not in ['BackSpace', 'Right', 'Left', 'Up', 'Down']:            self.entry.icursor(cursor)root = Tk()app = App(root)root.mainloop()

Some additional notes:

  • This version is using a StringVar() so that it's possible to both grab and set the contents of the entry, rather then being confined to just inserting.
  • Instead of hard-coding the dash positions, I abstracted them into their own list to make things a little less error-prone.
  • I added code to prevent the cursor position from going out of sync with the dashes. Notice that the cursor logic is completely independent of the logic to add the dashes. You could technically combine them into the same for loop, but I separated them for demonstration purposes.
  • I also added in some additional code to prevent the cursor automatically jumping to the end if the backspace or the arrow keys are pressed. You may also want to consider adding "Enter" as one of the keys to filter for.