I realize this is quite late for an answer but feel that I can give a lot simpler answer to this... it is really quite simple once you understand how it works.
Use the validating feature that comes with the Entry
widget.
Lets assume self
is a widget:
vcmd = (self.register(self.callback))
w = Entry(self, validate='all', validatecommand=(vcmd, '%P'))
w.pack()
def callback(self, P):
if str.isdigit(P) or P == "":
return True
else:
return False
You don't need to include all of the substitution codes: ('%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W'
), only the ones you'll use are necessary.
The Entry
widget returns a string so you will have to somehow extract any digits in order to separate them from other characters. The easiest way to do this is to use str.isdigit()
. This is a handy little tool built right into python's libraries and needs no extra importing and it will identify any numerics (digits) that it finds from the string that the Entry
widget returns.
The or P == ""
part of the if statement allows you to delete your entire entry, without it, you would not be able to delete the last (1st in entry box) digit due to '%P'
returning an empty value and causing your callback to return False
. I won't go into detail why here.
validate='all'
allows the callback to evaluate the value of P
as you focusin
, focusout
or on any key
stroke changing the contents in the widget and therefore you don't leave any holes for stray characters to be mistakenly entered.
In all, to make things simple. If your callback returns True
it will allow data to be entered. If the callback returns 'False` it will essentially 'ignore' keyboard input.
Check out these two references. They explain what each substitution code means and how to implement them.
http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/entry-validation.html
http://stupidpythonideas.blogspot.ca/2013/12/tkinter-validation.html
EDIT:
This will only take care of what is allowed in the box. You can, however, inside the callback, add whatever value P
has to any variable you wish.