In this code, I have a bunch of seats (ToggleButtons) and I want to count the no. of togglebuttons that are selected or switched ON when pressing the Button "Counter". I'm not sure if, for getting the result, I must individually Call a function from all the ToggleButtons (seats) or Call a single function in the main button "Counter". Also if possible, I need their Ids printed too.
Main Code:
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.uix.screenmanager import Screen,ScreenManager
class Main(Screen):
def counter(self,widget):
pass # what to put here? or do u have any other method
class Manager(ScreenManager):
pass
kv=Builder.load_file("test2.kv")
screen=Manager()
screen.add_widget(Main(name="main"))
class Test(App):
def build(self):
return screen
Test().run()
Kv Code:
<Main>:
name: "main"
FloatLayout:
id: Fl2
Button:
id: counter1
text: "Counter"
size_hint: (.25,.1)
pos_hint: {"center_x":.5,"center_y":.3}
on_press:
root.counter(self) # this should count no. of buttons that are ON i.e. the selected buttons
ToggleButton:
id: Seat_A2
color: (0,0,0,0)
text: "Seat_A2"
size_hint: (.0225,.0120)
pos_hint: {"center_x":.4,"center_y":.75}
background_color: (1,1,1,1)
on_state:
root.count(self) #i'm not sure if this func needs to be called individually
on all the toggle buttons or just one func in the counter button (i.e. root.counter(self))... idk the method...
ToggleButton:
id: Seat_A3
color: (0,0,0,0)
text: "Seat_A3"
size_hint: (.0225,.0120)
pos_hint: {"center_x":.4225,"center_y":.75}
background_color: (1,1,1,1)
on_state:
root.count(self)
ToggleButton:
id: Seat_A6
color: (0,0,0,0)
text: "Seat_A6"
size_hint: (.0225,.0120)
pos_hint: {"center_x":.4900,"center_y":.75}
background_color: (1,1,1,1)
on_state:
root.count(self)
ToggleButton:
id: Seat_A7
color: (0,0,0,0)
text: "Seat_A7"
size_hint: (.0225,.0120)
pos_hint: {"center_x":.5120,"center_y":.75}
background_color: (1,1,1,1)
on_state:
root.count(self)
ToggleButton:
id: Seat_A10
color: (0,0,0,0)
text: "Seat_A10"
size_hint: (.0225,.0120)
pos_hint: {"center_x":.5800,"center_y":.75}
background_color: (1,1,1,1)
on_state:
root.count(self)
ToggleButton:
id: Seat_A11
color: (0,0,0,0)
text: "Seat_A11"
size_hint: (.0225,.0120)
pos_hint: {"center_x":.6025,"center_y":.75}
background_color: (1,1,1,1)
on_state:
root.count(self)
You can process the children of the FloatLayout
that contains the ToggleButtons
, like this:
def counter(self,widget):
toggles = []
for child in self.ids.Fl2.children:
if isinstance(child, ToggleButton):
if child.state == 'down':
toggles.append(child.text)
print(len(toggles), 'ToggleeButtons active:', toggles)