Python kivy在on_press上将变量从一个类更新到另一个类

nwo49xxi  于 2023-01-19  发布在  Python
关注(0)|答案(2)|浏览(122)

我在这里得到了一个简单的代码,但我不记得如何通过按下.kv文件中MainWidget中的按钮来更新类KomagomaAppaverage方法的set_value变量。在任何地方都找不到解决方案。感谢您的帮助。

class CircularProgressBarMath(AnchorLayout):
    set_value = 0

class CircularProgressBarPhysic(AnchorLayout):
    set_value = 75

class CircularProgressBarChemistry(AnchorLayout):
    set_value = 65

class MainWidget(Widget):
    pass

class KomagomaApp(App):
    def build(self):
        return MainWidget()

    def average(self):
        pass

和.kv文件:

<CircularProgressBarMath>:
    canvas.before:
        Color:
            rgb: (0.329, 0.298, 0.263)
        Line:
            width: 1.3
            ellipse: (self.x, self.y, self.width, self.height, 0, 270)

    canvas.after:
        Color:
            rgb: (0.827, 0.737, 0.557)
        Line:
            id: progress_bar_math
            width: 2.3
            ellipse: (self.x, self.y, self.width, self.height, 0, root.set_value*2.7)

<MainWidget>:
    BoxLayout:
        orientation: 'horizontal'
        size: root.width, root.height
        padding: 50

        BoxLayout:
            orientation: 'vertical'
            size_hint: 1, 1
            padding: 20

            AnchorLayout:
                anchor_x: 'center'
                size_hint: 1, 1

                Button:
                    text: '+'
                    font_size: '20px'
                    pos_hint: {'top': 0.1, 'right': 1}
                    size_hint: 0.1, 0.1
                    on_release: app.average()

                CircularProgressBarMath:
                    size_hint: None, None
                    size: 500, 500
                    pos_hint: {'center_x': 0.5, 'center_y': 0.5}

                CircularProgressBarPhysic:
                    size_hint: None, None
                    size: 420, 420
                    pos_hint: {'center_x': 0.5, 'center_y': 0.5}

                CircularProgressBarChemistry:
                    size_hint: None, None
                    size: 340, 340
                    pos_hint: {'center_x': 0.5, 'center_y': 0.5}

我尝试了我在这里看到的多种东西,但没有办法使它工作。

ndh0cuux

ndh0cuux1#

id赋给您的自定义小部件并使用它。

CircularProgressBarMath:
    id: first_bar
    size_hint: None, None
    size: 500, 500
    pos_hint: {'center_x': 0.5, 'center_y': 0.5}

在平均函数中:

def build(self):
    # Save the main widget as a class variable
    self.root = MainWidget()
    return self.root

def average(self):
    self.root.ids.first_bar.set_value = 123
cngwdvgl

cngwdvgl2#

首先,您必须通知Kivy 'set_value'是Kivy的小部件属性类型。

from kivy.properties import NumericProperty

class CircularProgressBarMath(AnchorLayout):
    set_value = NumericProperty(0)  # instead of: set_value = 0

然后在kv文件中指定自定义小部件示例的id:

CircularProgressBarMath:
    id: my_bar

现在您可以像往常一样修改小工具的属性。小工具将在属性更改时自动更新:

def average(self):
    self.root.ids.my_bar.set_value += 5

相关问题