0

I'm new to GUI programming with python and I need a simple example about how to change GUI language based on .po files (that I AM able to generate) located inside the project. I'm using GNOME Builder for this task.

What I'd like is to load the gui definition from xml as produced by builder (or Glade) and let the program change texts based on my computer's locale/language.

test
  |
  |- po
  |  |- it.po
  |  |- en.po
  |  |- ...
  |
  |- src
  |  |- test.in 
  |  |- main.py
  |  |- window.py
  |  |- window.ui
  |  |- ...

This the file containing the main UI calss

#window.py
from gi.repository import Gtk


@Gtk.Template(resource_path='/path/to/ui/window.ui')
class TestWindow(Gtk.ApplicationWindow):
    __gtype_name__ = 'TestWindow'

    label = Gtk.Template.Child()


    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        print(_("hello"))

I discovered that changing the language of strings I put inside the code is as simple as writing

_("some string")

So when loading window.py I get "ciao" in the terminal (italian for hello). But I can't seem to change the language of GUI's widgets, for instance I see "Random Text" and not "Testo a caso" (again, italian translation).

Is there any parameter I can pass to Gtk.Template, or some python magic I can do to modify this behaviour?

  • Do you know about the `translatable=yes` parameter for XML entries? See for example the UI code in here: https://python-gtk-3-tutorial.readthedocs.io/en/latest/builder.html – nielsdg Oct 25 '20 at 13:47
  • Yes, I set it for all widgets that contain text, but it doesn't solve the problem unfortunately – Federico Marchetti Oct 25 '20 at 14:57

1 Answers1

0

First create a standard locales directory in your project:

locales
 ├── it
 │   └── LC_MESSAGES
 │       ├── messages.mo
 │       └── messages.po
 ├── fa
 │   └── LC_MESSAGES
 │       ├── messages.mo
 │       └── messages.po
 └── messages.pot #the English one

Then use gettext (for python strings) and locale (for xml strings) modules:

import gettext
import locale

locale_dir = LOCALE_DIR
locale.setlocale(locale.LC_ALL, '')
locale.bindtextdomain('messages', locale_dir)
gettext.bindtextdomain('messages', locale_dir)
gettext.textdomain('messages')
_ = gettext.gettext
Danial Behzadi
  • 161
  • 1
  • 10