views:

191

answers:

1

Hi,

Does anybody know how to create a text field using PyGTK that only accepts number. I am using Glade to build my UI.

Cheers,

+2  A: 

I wouldn't know about a way to do something like this by simple switching a settings, I guess you will need to handle this via signals, one way would be to connect to the changed signal and then filter out anything that's not a number.

Simple approach(untested but should work):

class NumberEntry(gtk.Entry):
    def __init__(self):
        gtk.Entry.__init__(self)
        self.connect('changed', self.on_changed)

    def on_changed(self, *args):
        text = self.get_text().strip()
        self.set_text(''.join([i for i in text if i in '0123456789']))

If you want formatted Numbers you could of course go more fancy with a regex or something else, to determine which characters should stay inside the entry.

EDIT
Since you may not want to create your Entry in Python I'm going to show you a simple way to "numbify" an existing one.

    def numbify(widget):
        def filter_numbers(entry, *args):
            text = entry.get_text().strip()
            entry.set_text(''.join([i for i in text if i in '0123456789']))

        widget.connect('changed', filter_numbers)

    # Use gtk.Builder rather than glade, you'll need to change the format of your .glade file in Glade accordingly
    builder = gtk.Builder()
    builder.add_from_file('yourprogram.glade')
    entry = builder.get_object('yourentry')

    numbify(entry)
Ivo Wetzel
Thank you for the suggestion. I am using text field to allow user specify number of hours or minute. I am looking at alternatives other than writing a validation for the user input. I will try to implement your suggestion and see how things goes.
zfranciscus