2

我有 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'

我不明白如何使用bindwith StringProperty

4

1 回答 1

1

好的,我找到了一个受@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()
    ...

这并不容易……对我来说

于 2015-02-28T19:25:25.023 回答