ScrolledText (over Tkinter.Text) validation
Jeff Epler
jepler at unpythonic.net
Mon May 20 14:02:16 EDT 2002
By returning the string "break" from a binding, you can stop further
processing of events, as described in the Tk "bind" manpage.
You would start with something like
def myfunc(evt):
k = evt.char
if k in "PERU": return
return "break"
aText = Text()
aText.bind("<KeyPress>", myfunc)
However, 'myfunc' will be executed even when the key is one such as
<Tab>, <Home>, or another key to be treated specially. For each such
key, you need a binding of the form
aText.bind("<Tab>", "# nothing")
as well as bindings to ignore modified keys
aText.bind("<Shift-Key>", "# nothing")
If you use an Entry instead of a Text, you can use textvariable= to link
the value in the entry to some Python instance. I'm not familiar with
doing this in Python, but the code might look something like this:
import Tkinter, re
class MyVariable(Tkinter.StringVar):
def __init__(self, master=None):
Tkinter.StringVar.__init__(self, master)
self.value = ""
self.trace = self.trace_variable("w", self._validate)
def __del__(self):
self.trace_vdelete("w", self.trace)
def _validate(self, name1, name2, op):
self.validate(self.get(), self.value)
self.value = self.get()
def validate(self, new_value, old_value):
self.set(new_value)
class PERUVariable(MyVariable):
def validate(self, new_value, old_value):
if re.match("^[PERU]*$", new_value):
self.set(new_value)
else:
self.set(old_value)
app = Tkinter.Tk()
aEntry = Tkinter.Entry(textvariable=PERUVariable(app))
aEntry.pack()
app.mainloop()
Jeff
More information about the Python-list
mailing list