views:

34

answers:

1

I'm trying to make my pygtk application behave the way openoffice calc does, regarding the decimal point. This means that when receiving a KP_Decimal key (the dot in the keypad) I want my entries to show whatever the decimal point is in the current locale (dot or comma, appropriately).

I've searched for a long while now, and I haven't been able to find how to do this. I can capture the key_press_event in the Gtk.Entry, and check for a KP_Decimal, and I can get the current locale setting for decimal point; but I don't know how to transform the dot to comma if needed.

I want this change to be global to the app, and not specific to certain entries, so it'd be better if it could be done through something more general, like input methods. I've been reading about them as well, and I couldn't find a way to use them how I want either.

+1  A: 

One way you could do this is by subclassing gtk.Entry, like so:

import gtk
import locale

class NumericEntry(gtk.Entry):
    __gsignals__ = {
        'key_press_event': 'override'
    }
    def do_key_press_event(self, event):
        if event.keyval == gtk.gdk.keyval_from_name('KP_Decimal'):
            event.keyval = int(gtk.gdk.unicode_to_keyval(ord(locale.localeconv()['decimal_point'])))
        gtk.Entry.do_key_press_event(self, event)

I haven't fully tested this, so there may be one or two edge cases, but it seems to work fine for me.

The nice thing about using a subclass is that it's then easy to replace your existing widgets - just use NumericEntry rather than gtk.Entry whenever you need a text entry with this behaviour.

Hope this helps!

Donald Harvey