python - Kivy ToggleButton行为

标签 python kivy

我尝试在两个或多个标签(例如单选按钮)之间建立切换。到目前为止,它可以使用 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'

有没有办法获得像单选按钮这样的行为?

最佳答案

有一个allow_no_selection 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()

关于python - Kivy ToggleButton行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33569682/

相关文章:

linux - Ubuntu 中的 Buildozer 启动问题为 'command not found'

python - xarray 在二维坐标上选择

python - 将内存中的 ZipFile 对象加载为 KivyImage

Python+kivy+SQLite : How to use them together

python - `scipy.stats.binned_statistic` 分箱值的标准差

python - Kivy:延迟交易中属性/设置属性的更改事件

python - 使用 Kivy 创建 sqlite3 数据库

python - 无法在 python :3. 4 docker 容器中导入 lxml

python - 将 curses 与 colorama 结合使用

python - 通过子进程库使用 python 执行进程