python kivy : 如何使切换按钮与轮播一起工作

python kivy : How to make switch Button work with carousel

我得到:

AttributeError: 'Carousel' object has no attribute 'switch_on'

每当我尝试点击按钮时出错

--------main.py----------

class main(App):
    def build(self):



        class SampBoxLayout(BoxLayout):


            # For Switch
            def switch_on(self, instance, value):
                if value is True:
                    print("Switch On")
                else:
                    print("Switch Off")



        return Carousel()



sample_app = kv_main()
sample_app.run()

------------main.kv-------------

:

Label:
    text: "Page 1"
    size_hint: 1, .1
    width :100

    SampBoxLayout:


        # ----------Switch ----------
        BoxLayout:

            BoxLayout:
                orientation: "horizontal"
                size_hint_x: .25
                CustLabel:
                    text: "On / Off"

                    Switch:
                        id: switch_id
                        on_active: root.switch_on(self, self.active)# <--need help on this


Label:
    text: "Page 2"
    size_hint: 1, .1
    width :100

    Button:
        text: "Button 2.1"
        size_hint: None, None
        width :100



Label:
    text: "Page 3"
    size_hint: 1, .1
    width :100

    Button:
        text: "Button 3.1"
        size_hint: None, None
        width :100

您正在使用 root.switch_on。如错误所示,您的根 class 是轮播。因为 SampBoxLayout 不是 root,你应该给 SampBoxLayout 一个 id,然后用它的 id 调用它。
根据您的示例编辑:

SampBoxLayout:
    id: samp
    BoxLayout:

        BoxLayout:
            orientation: "horizontal"
            size_hint_x: .25
            CustLabel:
                text: "On / Off"

                Switch:
                    id: switch_id
                    on_active: samp.switch_on(self, self.active)

不知道是不是你发帖的时候做错了,或者你的代码真的是这个样子的。但是你不应该在你的应用程序中定义 classes class。将 classes 保持在顶层以在 kv.
中访问它们 而且您的 kv 代码不寻常。您将小部件放在标签中。