这是我的示例 Glade/GtkBuilder/Gtk 应用程序。我定义了一个函数xml_gettext,它透明地翻译glade xml 文件并作为字符串传递给gtk.Builder 实例。
import mygettext as gettext
import os
import sys
import gtk
from gtk import glade
glade_xml = '''<?xml version="1.0" encoding="UTF-8"?>
<interface>
<!-- interface-requires gtk+ 3.0 -->
<object class="GtkWindow" id="window1">
<property name="can_focus">False</property>
<signal name="delete-event" handler="onDeleteWindow" swapped="no"/>
<child>
<object class="GtkButton" id="button1">
<property name="label" translatable="yes">Welcome to Python!</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<property name="use_action_appearance">False</property>
<signal name="pressed" handler="onButtonPressed" swapped="no"/>
</object>
</child>
</object>
</interface>'''
class Handler:
def onDeleteWindow(self, *args):
gtk.main_quit(*args)
def onButtonPressed(self, button):
print('locale: {}\nLANGUAGE: {}'.format(
gettext.find('myapp','locale'),os.environ['LANGUAGE']))
def main():
builder = gtk.Builder()
translated_xml = gettext.xml_gettext(glade_xml)
builder.add_from_string(translated_xml)
builder.connect_signals(Handler())
window = builder.get_object("window1")
window.show_all()
gtk.main()
if __name__ == '__main__':
main()
我已将我的语言环境目录归档到 locale.zip,它包含在 pyz 捆绑包中。
这是locale.zip的内容
(u'/locale/fr_FR/LC_MESSAGES/myapp.mo',
u'/locale/en_US/LC_MESSAGES/myapp.mo',
u'/locale/en_IN/LC_MESSAGES/myapp.mo')
为了将 locale.zip 作为文件系统,我使用来自fs 的 ZipFS。
幸运的是 Python gettext 不是 GNU gettext。 gettext 是纯 Python,它不使用 GNU gettext 而是模仿它。 gettext有两个核心功能find和translation。我在名为mygettext 的单独模块中重新定义了这两个,以使它们使用来自ZipFS 的文件。
gettext 使用 os.path 、os.path.exists 和 open 来查找文件并打开它们,我将它们替换为 fs 模块中的等效文件。
这是我的申请内容。
pyzzer.pyz -i glade_v1.pyz
# A zipped Python application
# Built with pyzzer
Archive contents:
glade_dist/glade_example.py
glade_dist/locale.zip
glade_dist/__init__.py
glade_dist/mygettext.py
__main__.py
因为pyz 文件有文本,通常是一个shebang,前置,我在以二进制模式打开pyz 文件后跳过了这一行。应用程序中想要使用gettext.gettext 函数的其他模块,应从mygettext 导入zfs_gettext,并使其成为_ 的别名。
这里是mygettext.py。
from errno import ENOENT
from gettext import _expand_lang, _translations, _default_localedir
from gettext import GNUTranslations, NullTranslations
import gettext
import copy
import os
import sys
from xml.etree import ElementTree as ET
import zipfile
import fs
from fs.zipfs import ZipFS
zfs = None
if zipfile.is_zipfile(sys.argv[0]):
try:
myself = open(sys.argv[0],'rb')
next(myself)
zfs = ZipFS(ZipFS(myself,'r').open('glade_dist/locale.zip','rb'))
except:
pass
else:
try:
zfs = ZipFS('locale.zip','r')
except:
pass
if zfs:
os.path = fs.path
os.path.exists = zfs.exists
open = zfs.open
def find(domain, localedir=None, languages=None, all=0):
# Get some reasonable defaults for arguments that were not supplied
if localedir is None:
localedir = _default_localedir
if languages is None:
languages = []
for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
val = os.environ.get(envar)
if val:
languages = val.split(':')
break
if 'C' not in languages:
languages.append('C')
# now normalize and expand the languages
nelangs = []
for lang in languages:
for nelang in _expand_lang(lang):
if nelang not in nelangs:
nelangs.append(nelang)
# select a language
if all:
result = []
else:
result = None
for lang in nelangs:
if lang == 'C':
break
mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
mofile_lp = os.path.join("/usr/share/locale-langpack", lang,
'LC_MESSAGES', '%s.mo' % domain)
# first look into the standard locale dir, then into the
# langpack locale dir
# standard mo file
if os.path.exists(mofile):
if all:
result.append(mofile)
else:
return mofile
# langpack mofile -> use it
if os.path.exists(mofile_lp):
if all:
result.append(mofile_lp)
else:
return mofile
# langpack mofile -> use it
if os.path.exists(mofile_lp):
if all:
result.append(mofile_lp)
else:
return mofile_lp
return result
def translation(domain, localedir=None, languages=None,
class_=None, fallback=False, codeset=None):
if class_ is None:
class_ = GNUTranslations
mofiles = find(domain, localedir, languages, all=1)
if not mofiles:
if fallback:
return NullTranslations()
raise IOError(ENOENT, 'No translation file found for domain', domain)
# Avoid opening, reading, and parsing the .mo file after it's been done
# once.
result = None
for mofile in mofiles:
key = (class_, os.path.abspath(mofile))
t = _translations.get(key)
if t is None:
with open(mofile, 'rb') as fp:
t = _translations.setdefault(key, class_(fp))
# Copy the translation object to allow setting fallbacks and
# output charset. All other instance data is shared with the
# cached object.
t = copy.copy(t)
if codeset:
t.set_output_charset(codeset)
if result is None:
result = t
else:
result.add_fallback(t)
return result
def xml_gettext(xml_str):
root = ET.fromstring(xml_str)
labels = root.findall('.//*[@name="label"][@translatable="yes"]')
for label in labels:
label.text = _(label.text)
return ET.tostring(root)
gettext.find = find
gettext.translation = translation
_ = zfs_gettext = gettext.gettext
gettext.bindtextdomain('myapp','locale')
gettext.textdomain('myapp')
不应调用以下两个,因为 glade 不使用 Python gettext。
glade.bindtextdomain('myapp','locale')
glade.textdomain('myapp')