Reputation: 1095
I try to build a toggle between two or more labels like radio buttons. It work so far with the ToggleButtonBehavior to change the state between the group but when I click the selected item it get deselected and should not do it.
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'
Is there a way to get a behavior like a radio button?
Upvotes: 1
Views: 1028
Reputation: 8747
There is a 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
After setting it to False
and using a group everything starts to work as intended:
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()
Upvotes: 1