如何通过不同的 类 或 kivy 中的根小部件传递变量?

How do I pass variables through different classes or root widgets in kivy?

我正在创建一个应用程序,我在其中确定一个 class 中的变量并需要将其传输到另一个 class。我想使用 id 但这不适用于不同的根小部件。然后我发现了有关工厂的信息,它看起来很有前途并且似乎有点工作,但是当我更新 PopupColor class 中的变量时,它不会在我的 DrawScreen class 中更新。

这是代码。

py:

class PopupColor(Popup):
    color = [0,0,0,1]
    def on_press_dismiss(self, colorpicker, *args):
        print(self.color)
        self.dismiss()
        self.color = colorpicker.color
        print(self.color)

class DrawScreen(Screen):
    def testy(self):
        self.color = Factory.PopupColor().color
        print(self.color)

kv:

<PopupColor>:
    title: 'Pick a Color'
    size_hint: 0.75, 0.75
    id: popupcolor

    BoxLayout:
        padding: 5
        spacing: 5
        orientation: 'vertical'

        ColorPicker:
            id: colorpicker
            size_hint: 1.0, 1.0

        Button:
            text: 'Choose Color'
            size_hint: 1, 0.2
            on_release: popupcolor.on_press_dismiss(colorpicker)

<DrawScreen>: 

    Button:
        size_hint: 0.2,0.1
        font_size: 30
        text: "Back"
        on_release: Factory.PopupColor().open()

    ColorButton:
        text: "Test"
        pos_hint:{"center_x":0.5, "y":0.1}
        on_release: root.testy()

那么我该怎么做,离我还有多远?

编辑:所以看起来错误并不是真正的工厂部分,而是 PopupColor 中的变量不会永久改变。

问题是当你更改属性时,你使用 self,它指的是这个实例。
但是由于你新建了一个PopupColor对象,所以每次打开popup的时候,都需要把color当作一个共享变量。
所以你可以这样改变颜色:

PopupColor.color = colorpicker.color

这样您就可以将属性 color 视为与所有 PopupColor 对象共享。