开发者

Creating a pygtk text field that only accepts number

Does 开发者_开发百科anybody know how to create a text field using PyGTK that only accepts number. I am using Glade to build my UI.

Cheers,


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)


If you don't want to sanitize user input, avoid allowing text input entirely. If you're trying to collect hours and minutes, how about spin buttons or other widgets where you can limit the user's choice.

Check out the spinbutton example: http://www.pygtk.org/pygtk2tutorial/examples/spinbutton.py


Convert your text to a number and in case it doesn't handle the error and set the text to an empty string.

You can generalize this to match a regular expression the way you want

try:
    val = float(entry.get_text())
    entry.set_text(str(val))
except ValueError:
    entry.set_text('')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜