2015-11-06 97 views
1

我嘗試在單選按鈕之類的兩個或多個標籤之間建立切換。它到目前爲止與ToggleButtonBehavior一起工作來改變組之間的狀態,但是當我點擊選中的項目時,它將被取消選擇,不應該這樣做。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' 

有沒有辦法讓行爲像一個單選按鈕?

回答

1

有一個allow_no_selection property

這指定了一個組中的微件是否允許沒有選擇即 所有內容被取消選擇。

allow_no_selection是BooleanProperty默認值爲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()