【问题标题】:kivy: How to use StringProperty and bind()?kivy:如何使用 StringProperty 和 bind()?
【发布时间】:2015-02-28 16:34:20
【问题描述】:

我有 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 一起使用。

【问题讨论】:

    标签: python kivy bind object-properties


    【解决方案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()
        ...
    

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

    【讨论】:

      猜你喜欢
      • 2017-02-21
      • 2019-02-14
      • 2015-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-24
      相关资源
      最近更新 更多