I am writing a program in python that will take in specific formats, a Phone number and dollar/cent values. How can I make tkinter have default value which is permanent, not deletable. For example (XXX)-XXX-XXXX?
basically you can add an entry to the widget but the entry is defined the permanent value like when its empty it looks like (_ _ _)-___-____ when it has text it looks like (434)-332-1234
If I understand you correctly, you want some sort of template in which a user can type his/her information but is restricted to some format. You can do this using the Entry's validatecommand
. Basically, this calls a function whenever something is being inserted and can return True or False to accept or reject the change. For more information about how this works see this answer by Bryan Oakley.
In your case, you'd want the function to return True whenever something has the format (...)-...-....
, which you can check with a regular expression. The regular expression you could use is ^\(\d{0,3}\)-\d{0,3}-\d{0,4}$
.
I'll explain it for you. ^
means that that should be the beginning of the string, \(
means there should be a (
, \d{0,3}
means that there can be 0 to 3 numbers (I assumed you only want numbers, if not you can change it to \w
to accept any letter or number). Then comes \)
which means )
, a -
which literally means -
, some digits and a -
again and at the end a $
which means that should be the end of the string.
You can use this regular expression in the validatecommand
function to check if the entry has the right format by using:
import Tkinter as tk
import reclass MyApp():def __init__(self):self.root = tk.Tk()vcmd = (self.root.register(self.OnValidate), '%P')self.entry = tk.Entry(self.root, validate="key", validatecommand=vcmd)self.entry.pack()self.prog = re.compile('^\(\d{0,3}\)-\d{0,3}-\d{0,4}$')self.entry.insert(0, '()--')self.root.mainloop()def OnValidate(self, P):if self.prog.match(P):result = Trueelse:result = Falsereturn resultapp=MyApp()
I used the before linked answer as template, removed everything that you don't need for your particular case and inserted the regular expression. Because it only returns True when the string matches the pattern, only edits that fit in the pattern are allowed.