Creating a pygtk text field that only accepts a number

Does anyone know how to create a text field using PyGTK that only accepts a number. I use Glade to create my user interface.

Greetings

+3
source share
3 answers

I would not know about a way to do something like this by simply switching settings, I think you would need to process this through signals, one way would be to connect to a signal changed, and then filter out something that is not a number.

A 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']))

Numbers, , , - , , .


Python, "numbify" .

    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)
+7

, .

, ,

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

Source: https://habr.com/ru/post/1743109/


All Articles