【问题标题】:How do I pass variables through different classes or root widgets in kivy?如何通过 kivy 中的不同类或根小部件传递变量?
【发布时间】:2017-12-06 20:25:48
【问题描述】:

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

这是代码。

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 中的变量不会永久更改。

【问题讨论】:

    标签: python kivy kivy-language


    【解决方案1】:

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

    PopupColor.color = colorpicker.color
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-11
      • 2012-05-26
      • 2021-07-08
      • 2014-12-16
      相关资源
      最近更新 更多