Kivy ToggleButton贝维

2024-10-04 01:27:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在两个或多个标签之间建立一个切换,比如单选按钮。到目前为止,它可以通过ToggleButtonBehavior来改变组之间的状态,但是当我单击所选项目时,它将被取消选择,不应该这样做。在

class SelectButton(ToggleButtonBehavior, Label):
    active = BooleanProperty(False)
    def __init__(self, **kwargs):
        super(SelectButton, self).__init__(**kwargs)

        self.text='off'
        self.color=[1,0,1,1]

        self.bind(state=self.toggle)

    def toggle(self, instance, value):
        if self.state == 'down':
            self.text = 'on'
        else:
            self.text = 'off'

有没有办法让你的行为像单选按钮?在


Tags: 项目textselfinit状态def标签按钮
1条回答
网友
1楼 · 发布于 2024-10-04 01:27:02

有一个^{} property

This specifies whether the widgets in a group allow no selection i.e. everything to be deselected.

allow_no_selection is a BooleanProperty and defaults to True

将其设置为False并使用组后,一切都开始按预期工作:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.behaviors import ToggleButtonBehavior
from kivy.properties import BooleanProperty
from kivy.lang import Builder

Builder.load_string('''
<MyWidget>:
    SelectButton:
        state: 'down'
        text: 'on'
    SelectButton
        state: 'normal'
        text: 'off'
    SelectButton
        state: 'normal'
        text: 'off'
''')

class SelectButton(ToggleButtonBehavior, Label):
    active = BooleanProperty(False)

    def __init__(self, **kwargs):
        super(SelectButton, self).__init__(**kwargs)

        self.allow_no_selection = False

        self.group = "mygroup"
        self.color=[1,0,1,1]

        self.bind(state=self.toggle)

    def toggle(self, instance, value):
        if self.state == 'down':
            self.text = 'on'
        else:
            self.text = 'off'

class MyWidget(BoxLayout):
    pass

class MyApp(App):
    def build(self):
        return MyWidget()

if __name__ == '__main__':
    MyApp().run()

相关问题 更多 >