i18n and GUI under Windows

Fred Pacquier xnews2 at fredp.lautre.net
Tue Sep 7 16:19:37 EDT 2004


andre.roberge at ns.sympatico.ca (Andr? Roberge) said :

> In short: I'm looking for a *simple* example of how to write a program
> that can have its GUI in at least two languages under Windows ...
> using only Python, of course!
 
Well, André, if you really want *simple* (as in *simplistic*, *simple-
minded* or *can't-get-no-simpler* :) I have something that does just that 
(english/french under wxPython)... Note that most of the other 
suggestions that were given in the rest of this thread are probably 
better for "serious" work ; but going all the way to GNU gettext is a bit 
involved, and quick-n-dirty hacks such as this can be enough for simple 
apps and a handful of languages...

It goes something like this (purists please avert your eyes :-),


* at the beginning of the main module I have these statements :

#---------------------------------------------------------------------
# determine locale and set global french/english flag
# import localized strings and define gettext-like '_' function

import locale
lang, cp = locale.getdefaultlocale()
lang = lang[:2]
if not lang == 'fr' : lang = 'en'

import l10n

def _(msg) :
    if lang == 'fr' :
        return msg
    else :
        return l10n.trans[lang].get(msg, msg)
        # if no translation found return the original (fr) string


* afterwards in your code, everywhere a string appears that needs to be 
localized, wrap it in a _() function call (this is the convention set by 
GNU gettext that everyone generally uses even if they don't use gettext 
itself :)
i.e.: "André" becomes _("André")


* module l10n.py is just one big dictionary with language locales as 
strings and dictionaries of original/translated strings as values, as in:

# MyApp localized strings
# -*- coding: iso-8859-1 -*-

trans = {}

trans['en'] = {
"André" : "Andrew",
"Bonjour" : "Hello",
"Dictateur Bienveillant A Vie" : "BDFL" }


* and that's it. You'll notice that in my example the original version is 
in French and English is a translation. That's because it was grafted as 
an afterthought/experiment onto already finished code. Forward-thinking 
authors may want to do it the other way around, especially if they expect 
to get help with other languages :-)

Then it's not too hard to add, say, a trans['de'] dict to l10n.py and 
change the locale test above to use it. If automatic detection is not 
adequate, then the GUI needs to provide a widget or dialog for the user 
to set the desired language...

HTH,
fp

-- 
YAFAP : http://www.multimania.com/fredp/



More information about the Python-list mailing list