Formatting Text into a Time Format as the user Types
I'm trying to format text into the standard time format of 00:00:00
in a Tk.Entry textbox, as the user types in the numbers.
I understand that Tkinter is not the easiest, nor best optimized framework to format text while the user types, but I've managed to get this far:
from Tkinter import *
class Application(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.createWidgets()
def createWidgets(self):
sv = StringVar()
sv.trace("w", lambda name, index, mode, sv=sv: self.entryUpdateEndHour(sv))
endHourEntry = Entry(self, textvariable=sv)
endHourEntry.pack()
def entryUpdateEndHour(self, sv):
global x
x = sv.get()[0:2] + ':'
y = x + sv.get()[3:5] + ':'
z = y + sv.get()[6:8]
sv.set(z)
root = Tk()
app = Application(master=root)
app.mainloop()
This prints out exactly what I want (12:45:67
), but the live formatting is bad. For example, in typing two numbers I get 12:::
in the textbox, and it skips every 3rd number I type in, since it replaces it with a :
.
I would be very grateful if someone has any work arounds or solutions to this answer. Thanks in advance.