[pygtk] Using changed event
Richard Taylor
rjt-pygtk at thegrindstone.me.uk
Tue Jan 31 06:10:11 WST 2006
On Monday 30 Jan 2006 15:24, Nicholas Wieland wrote:
> Hi *,
> I need to trap all non-digits in a gtk.Entry, to prevent hte user
> from inserting letters and symbols at all.
> I'm trying to use the 'changed' event, but it doesn't seem to work:
>
> def foo (self, widget):
> if re.match ('[A-Za-z,.\-+]', widget.get_text () [-1]):
> return True
>
> Any idea ?
>
> TIA,
You might find this useful, it is the Integer only edit widget from gramps
(www.gramps-project.org). It is based on the code in the FAQ.
class IntEdit(gtk.Entry):
"""An gtk.Edit widget that only allows integers."""
def __init__(self):
gtk.Entry.__init__(self)
self._signal = self.connect("insert_text", self.insert_cb)
def insert_cb(self, widget, text, length, *args):
# if you don't do this, garbage comes in with text
text = text[:length]
pos = widget.get_position()
# stop default emission
widget.emit_stop_by_name("insert_text")
gobject.idle_add(self.insert, widget, text, pos)
def insert(self, widget, text, pos):
if len(text) > 0 and text.isdigit():
# the next three lines set up the text. this is done because we
# can't use insert_text(): it always inserts at position zero.
orig_text = widget.get_text()
new_text = orig_text[:pos] + text + orig_text[pos:]
# avoid recursive calls triggered by set_text
widget.handler_block(self._signal)
# replace the text with some new text
widget.set_text(new_text)
widget.handler_unblock(self._signal)
# set the correct position in the widget
widget.set_position(pos + len(text))
Regards
Richard
--
You can normally find me on Jabber as RichardTaylor at jabber.org
More information about the pygtk
mailing list