python - 从另一个 .py 文件访问 Python 字典不会更新 Kivy 标签

标签 python dictionary kivy

我正在为我的应用程序进行语言翻译。从另一个 py 文件中的字典访问翻译对我来说最有意义。

从技术上讲,我可以访问字典值,但按下按钮时无法更改 KV 文件中的值。任何指导将不胜感激!

main.py

from kivy.app import App
from kivy.lang import Builder

kv_file = Builder.load_string("""
#:import pyfile pyfile
ScreenManager:
    id: manager
    Screen:
        GridLayout:
            cols:1
            rows:5
            Button:
                text: 'To English'
                on_release:
                    pyfile.rando().chosen_language = pyfile.rando().English
            Button:
                text: 'To Croatian'
                on_release:
                    pyfile.rando().chosen_language = pyfile.rando().Croatian
            Label:
                text:
                    pyfile.rando().chosen_language['MS First Button']
""")

class MyApp(App):

    def build(self):
        return kv_file

if __name__ == '__main__':
    MyApp().run()

pyfile.py

# -*- coding: utf-8 -*-
from kivy.properties import DictProperty

class rando(DictProperty):

    English = {'MS First Button': 'Take the Quiz'
    }

    Croatian = {'MS First Button': 'Učinite Kviz'
    }

    chosen_language = English

最佳答案

from kivy.app import App
from kivy.lang import Builder
from kivy.properties import DictProperty

kv_file = Builder.load_string("""
#:import pyfile pyfile
ScreenManager:
    id: manager
    Screen:
        GridLayout:
            cols:1
            rows:5
            Button:
                text: 'To English'
                on_release: app.translation_dict = app.English
            Button:
                text: 'To Croatian'
                on_release: app.translation_dict = app.Croatian

            Label:
                text:
                    app.translation_dict['MS First Button']
""")



class MyApp(App):

    English = {'MS First Button': 'Take the Quiz'}

    Croatian = {'MS First Button': 'Učinite Kviz'}

    translation_dict = DictProperty(English)

    def build(self):
        return kv_file

if __name__ == '__main__':
    MyApp().run()

您对 DictProperty 的使用是不正确的,属性仅在 EventDispatcher 中的类级别创建时才有效。它们实际上是一种特殊类型的 Python 对象,称为描述符,您可以查找它以了解它们是如何工作的。

上面的代码是快速调整,以显示一种可行的方法,就像有效逻辑流程的示例(未经测试)。

关于python - 从另一个 .py 文件访问 Python 字典不会更新 Kivy 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53842478/

相关文章:

python - 如何强制 py2app 以 32 位模式运行应用程序

java - 如何使用 jSTL 迭代 map ?

swift - 根据键和值对字典数组进行排序

Python Kivy Canvas 不会更新

python - Matplotlib imshow 和 kivy

Python + Flask 网络应用报告 "[Errno 9] Bad file descriptor"与 pexpect 模块

python - Keras 代码 Q-learning OpenAI gym FrozenLake 有问题

python - 如何将嵌套的字典键转换为字符串?

python - KeyError 在 kivy 中停止 App

python - 从 python 字符串加载模块而不执行代码