应用程序中的多语言支持

时间:2019-08-23 05:31:07

标签: python python-3.x

我正在尝试创建一个具有GUI的小工具。我想在界面中提供不同的语言。这就是为什么我考虑将每种语言的所有字符串写入文件并在创建gui时读取数据的原因。我担心这会占用大量内存并降低性能。 是否有实现此目的的好方法?

伪代码示例:

language_file = open(path)
title = language_file.title
text = language_file.text
button_text = language_file.btntext

window = tk.Tk()
la_title = tk.Label(window, text=title)
la_text  = tk.Label(window, text=text)
btn = tk.Button(window, text=button_text, command=close_window)

1 个答案:

答案 0 :(得分:0)

1。找到合适的文件格式。

某些格式比其他格式更适合。您需要可以在其中定义标签之类的东西,以及每种语言对应的值。您可以尝试使用csv格式。

2。将数据加载到python对象中

使用所有数据创建文件后,可以在程序开始时将其加载到python对象中。当您的文件不是很大,我的意思是巨大时,这应该不会花费太长时间。您打开文件并加载一些Python对象来使用它。

3。创建合适的python对象。

您想要的是类似字典的东西。您有一个标签,它是键,并且是一个取决于所选语言的值。因此,对于每种语言,您都可以拥有一本字典。或更嵌套的字典。 为了获得更好的访问权限,我将创建一个类来处理所有这些情况。

可以简化事情的可能事情。 (我将在稍后扩展这部分。并添加更多详细信息)

您可以:

  • 重写__getattr__方法,以便您可以编写:Language.header
  • 用语言词典扩展类的__dict__Language.header
  • 编写一个函数:Language.get_text("Header")Language.get_text("Header", "english")或...

字典示例(展开__dict__

class Language:

    def __init__(self, texts):
        self.texts = Texts
        print(dir(self)) # just for debug
        # Magic part
        self.__dict__.update(self.texts)
        print(dir(self)) # just for debug. Note the last entries

    @staticmethod
    def from_file(path, language):
        # comment the open part out if you just want to test this example without a file
        with open(path, r) as f:
             pass # Read content. Get all words of language
        texts = {"header": "My header", "label_username": "Username"}
        return Language(texts)

l = Language.from_file("Some path to a file", "English")
print(l.header)
print(l.label_username)
相关问题