根据其他四个 ToggleButton 的 "down" 状态激活 ToggleButton

Activate a ToggleButton based on the "down" state of four other ToggleButton 's

纠结了几天,决定向 kivy 社区提问!

目前正在想办法

-根据其他四个 ToggleButton 的切换状态激活一个 ToggleButton

这是界面图片:

激活 Toggle1、Toggle2、Toggle3 和 Toggle4 上的“向下”状态应该激活 MainToggle1

这是我目前的情况:

main.py
from kivy.app import App
from kivy.properties import StringProperty, BooleanProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.widget import Widget

class ExternalTrigger(BoxLayout):
    buttonState = BooleanProperty(False)
    def on_activated_state(self, widget):
        if widget.state == "normal":
            self.buttonState = False
        elif widget.state == "down":
            self.buttonState = True

class BoxLayoutExample(BoxLayout):
    pass

class BoxLayoutApp(App):
    pass

BoxLayoutApp().run()

BoxLayout.kv

BoxLayoutExample:

<ExternalTrigger@BoxLayout>:
    ToggleButton:
        text: "MainToggle1"
        on_state: root.on_activated_state(self)
        disabled: root.on_activated_state(self)

<BoxLayoutExample@PageLayout>:
    orientation: "vertical"
    BoxLayout:
        orientation: "horizontal"
        ExternalTrigger:
        GridLayout:
            size_hint: 2, 1
            cols: 2
            ToggleButton:
                background_color: (0,0,1)
                text: "Toggle1"
            ToggleButton:
                background_color: (0,1,0)
                text: "Toggle2"
            ToggleButton:
                background_color: (1,0,0)
                text: "Toggle3"
            ToggleButton:
                background_color: (7,1,3)
                text: "Toggle4"

不胜感激!

使用 id 属性 和 ToggleButton 的自定义 class。

您要添加的class:

class MyToggleButton(ToggleButton):
    # This method will check if all the ToggleButtons are "down" state
    def checkAllButtons(self, btn1, btn2, btn3, btn4):
        if (btn1.state == 'down') and (btn2.state == 'down') and (btn3.state == 'down') and (btn4.state == 'down'):
            return 'down'
        else:
            return 'normal'

在您的 .kv 文件中,将自定义 属性 添加到 class <ExternalTrigger@BoxLayout>: 并将其绑定到主 ToggleButton 的状态:

<ExternalTrigger@BoxLayout>:
    custom: 'normal'
    ToggleButton:
        text: "MainToggle1"
        on_state: root.on_activated_state(self)
        disabled: root.on_activated_state(self)
        state: root.custom

然后将 id 添加到每个 ToggleButton 并在四个 ToggleButton 处于“按下”状态时评估 on_press 事件(使用自定义 class 中创建的方法执行此操作)。

将您拥有的所有四个 ToggleButton 更改为以下内容:


MyToggleButton:
    id: but1  # Here obviously change the id, for example in ToggleButton2: id=but2
    background_color: (0,0,1)
    text: self.state
    on_press: ext.custom=self.checkAllButtons(but1,but2,but3,but4) #This remains the same for every ToggleButton