kivy:如何使用 StringProperty 和 bind()?

kivy: How to use StringProperty and bind()?

我有 2 个屏幕,由屏幕管理员管理。

我正在使用全局变量 CHOSEN_ITEM 来保存由第一个屏幕更改的字符串变量。

CHOSEN_ITEM 由第二屏幕显示。我知道必须使用 StringProperty 但我没有找到一个很好的例子,我自己可以理解,为此...

from kivy.properties import ObjectProperty, StringProperty
    ...
CHOSEN_ITEM = ''

class FirstScreen(Screen):
      ...
    def save_chosen(self):
        global CHOSEN_ITEM
        CHOSEN_ITEM = chosen_item
      ...

class SecondScreen(Screen):
      ...
    global CHOSEN_ITEM
    chosen_item = StringProperty(CHOSEN_ITEM)

    def on_modif_chosenitem(self):
        print('Chosen Item was modified')
    self.bind(chosen_item=self.on_modif_chosenitem)
    ...

然后错误是:

     File "_event.pyx", line 255, in kivy._event.EventDispatcher.bind (/tmp/pip-build-udl9oi/kivy/kivy/_event.c:3738)
 KeyError: 'chosen_item'

我不知道如何将 bindStringProperty 一起使用。

好的,我找到了一个受@inclement 启发的解决方案:Kivy ObjectProperty to update label text

from kivy.event import EventDispatcher
from kivy.properties import StringProperty
    ...
CHOSEN_ITEM = ''

class Chosen_Item(EventDispatcher):
    chosen = StringProperty('')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.chosen = 'Default String'
        self.bind(chosen=self.on_modified)

    def set_chosen_item(self, chosen_string):
        self.chosen = chosen_string

    def get_chosen_item(self):
        return self.chosen

    def on_modified(self, instance, value):
        print("Chosen item in ", instance, " was modified to :",value)  

class FirstScreen(Screen):
    global CHOSEN_ITEM
    CHOSEN_ITEM = Chosen_Item()
      ...
    def save_chosen(self):
      CHOSEN_ITEM.set_chosen_item(chosen_item) 
      ...

class SecondScreen(Screen):
      ...
    global CHOSEN_ITEM
    chosen_item = CHOSEN_ITEM.get_chosen_item()
    ...

这并不容易...对我来说