Search code examples
internationalizationpygtkgettext

PyGtk3 and Gettext - problem choosing the language at run-time


Long story short, when I thought the strings would be translated, nothing happens.

I have a PyGtk application and a module where I store all the strings that I want to be translated in the following way:

'''
    Strings module.
'''

....
CANCEL_BUTTON_TEXT = _("Cancel")
BACK_BUTTON_TEXT = _("Back")
....

And so on. So then they are used from other modules like:

'''
    View module.
'''

import strings

# Usage example
button.set_label(strings.CANCEL_BUTTON_TEXT)
button.set_tooltip(strings.TOOLTIP)
window_title.set_title(strings.WINDOW_TITLE)
...

I have created the necessary .mo files. This is the jerarquy I have:

  • /locales
    • /es
      • LC_MESSAGES
        • base.mo
        • base.po
    • /en
      • LC_MESSAGES
        • base.mo
        • base.po
    • base.pot

As the documentation says (https://docs.python.org/3/library/gettext.html), in my main.py I have the following lines:

import gettext
gettext.install('myapplication')

es_lang = gettext.translation('base', localedir='locales', languages=['es'])
en_lang = gettext.translation('base', localedir='locales', languages=['en'])

es_lang.install()

Then, in my application I have a button, that when is pressed, the following line is executed:

en_lang.install()

But the spanish language is still used on the widgets. Could anyone help me out?


Solution

  • So, what I was doing wrong is I was translating the strings but I wasn't updating the GTK Widgets labels, among other things.

    The way I solved this was:

    i) Created a class where I put all the strings I want to translate when the user selects a language. That class is the only one to import the gettext module.

    ii) When the user selects a language, a method of that class is called and it translates all strings to that language.

    iii) Another method outside that class updates all labels and widgets that use those strings.