我正在为我的应用程序进行语言翻译。从另一个 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/