我有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'
我不知道如何将bind
与StringProperty
一起使用。
答案 0 :(得分:0)
好的,我已经找到了@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()
...
对我而言,这并不容易