Reputation: 148
I have a radio button system set up to select a home team in a sports game analysis situation. The code is as follows below:
note the Button
s have been abstracted to focus on the question instead of the code
<NamingScreen>:
GridLayout:
cols: 3
rows: 4
Button:
Button:
Button:
Label:
text: 'HomeTeam?'
CheckBox:
id: team1_radio
active: True
group: "home deciders"
allow_no_selection: False
on_active:
root.manager.get_screen('name_screen').ids.team1_selected.text = 'Selected as\n Home'
root.manager.get_screen('name_screen').ids.team2_selected.text = ''
Label:
id: team1_selected
text: 'Selected as\n Home'
######## team 2 buttons from here
Button:
Button:
Button:
Label:
text: 'Home Team?'
CheckBox:
id: team2_radio
group: "home deciders"
allow_no_selection: False
on_active:
root.manager.get_screen('name_screen').ids.team2_selected.text = 'Selected as\n Home'
root.manager.get_screen('name_screen').ids.team1_selected.text = ''
Label:
id: team2_selected
text: ''
I now need to know which checkbox was selected. Is there a method that does something similar to the following
where group("home_deciders").selected
returns team1_radio
for example?
I know that it's possible to do it using functions in the python file to compare both active
values in each checkbox, but I am looking for a more elegant solution
Thanks in advance :)
Upvotes: 1
Views: 126
Reputation: 627
here is one way. With this solution,the Python method will be called one time and will be sent an argument that indicates which button is active.
One can save some of the business of the kivy file by defining a new class at the top of you Kivy file. It just avoids some of the repetitive lines.
<HomeDeciderCheckBox@CheckBox>
group: "home deciders"
allow_no_selection: False
# on_active: root.select_screen(self._num) if self.active else None
# OR
on_active: app.select_screen(self._num) if self.active else None
In your Kivy layout assign each check box with a unique number, _num and choose just one to be Active at initialization.
HomeDeciderCheckBox:
active: True
id: team1_radio
_num: 1
HomeDeciderCheckBox:
id: team2_radio
_num: 2
HomeDeciderCheckBox:
id: another_unique_id
_num: 3
In Python you can do the remaining logic. I think this is good design because you have separation of concerns in which your Python code has the logic and your kivy code (the gui) just shows how to lay out the graphics.
Python:
def select_screen(self, selection):
# and whatever other logic you need
print(f"{selection}")
Upvotes: 1