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