How to convert a key pressed into another in pygtk

I am trying to get the pygtk application to behave like openoffice calc does, relative to the decimal point. This means that when I get the KP_Decimal key (a dot on the keyboard), I want my records to show which decimal point is in the current locale (dot or comma, respectively).

I searched for a long time, and I could not find how to do this. I can capture key_press_event in Gtk.Entry and check KP_Decimal, and I can get the current locale setting for the decimal point; but I don’t know how to convert point to comma if necessary.

I want this change to be global for the application, and not specific to certain entries, so it would be better if it could be done using something more general, such as input methods. I also read about them, and I could not find a way to use them the way I want.

+4
source share
1 answer

One way to do this is to subclass gtk.Entry , for example:

 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 have not tested this completely, so there may be one or two edge cases, but it seems to work fine.

The best part about using the subclass is that it’s easy to replace existing widgets then - just use NumericEntry and not gtk.Entry whenever you need a text entry with this behavior.

Hope this helps!

+2
source

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


All Articles