【问题标题】:Kivy: Use a toggle button to change the state of another toggle buttonKivy:使用切换按钮更改另一个切换按钮的状态
【发布时间】:2017-05-26 07:49:09
【问题描述】:

例如,在 Kivy 语言中:

<MainToggle@ToggleButton>:
    on_state: # something that will change the state of the sub-toggle

<SubToggle@ToggleButton>:
    on_state: self.background_color = 0,0,0,1 # the sub-toggle button changes color 

【问题讨论】:

    标签: python kivy kivy-language


    【解决方案1】:

    您可以使用 kivy id 系统引用其他小部件。观察以下代码:

    from kivy.base import runTouchApp
    from kivy.lang import Builder
    
    runTouchApp(Builder.load_string("""
    <MainToggle@ToggleButton>:
    
    <SubToggle@ToggleButton>:
        on_state: self.background_color = 0,0,0,1 # the sub-toggle button changes color 
    
    BoxLayout:
        MainToggle:
            id: my_toggle1 # an id allows us to refer to this widget
            text: "Main Toggle"
            # change the other toggle's state using its id 
            on_state: my_toggle2.state = "down" if my_toggle2.state == "normal" else "normal"
        SubToggle:
            id: my_toggle2
            text: "Sub Toggle"
                """))
    

    这是一个极好的video 教程,它在一个实际示例中使用了 kivy id 系统。如果您对此有疑问,请回复。

    【讨论】:

    • 太棒了!这工作,感谢您的帮助。我遇到的另一个问题是当我尝试使用“MainToggle”来更改多个“SubToggle”按钮的状态时,而不仅仅是一个。我试图通过为所有 SubToggle 按钮提供相同的 id 来实现这一点,但是 MainToggle 似乎一次只影响一个 SubToggle。对此有什么想法吗?再次感谢。
    • 嗯,您似乎在这里尝试做一些棘手的事情,您确定您选择了正确的方法吗?无论如何,如果有许多 SubToggle 按钮并且您想以相同的方式更改它们,为什么不给您的 BoxLayout 一个 id,并且当您从 Python 代码插入 SubToggle 时,将它们添加到 ListProperty。然后您可以遍历该列表并执行for sub in sub_list: change_state(x) 或类似的操作。如果对您有帮助,请考虑接受我的原始答案。
    • 刚刚接受 :) 是的,我想做的是在菜单下列出项目列表。我希望能够单独单击项目按钮,并单击菜单按钮,以便将其下方的所有项目按钮的状态更改为“向下”位置。我一直在使用 kivy 语言插入所有切换按钮,但似乎我需要在 Python 端进行某种循环。
    • 如果您没有太多的 SubToggle,只需考虑给每一个单独的 id,然后让 MainToggle 单独更改每个 SubToggle 的状态 - 这就像我提出的一个有效的解决方案列表属性。清单一更简洁,如果您将来添加另一个 SubToggle,您将无需执行任何操作。如果您有疑问,我建议您先从个人 id 方法开始。
    猜你喜欢
    • 2020-01-04
    • 2011-12-25
    • 1970-01-01
    • 1970-01-01
    • 2017-09-26
    • 1970-01-01
    • 2020-08-24
    • 2020-09-20
    相关资源
    最近更新 更多