In this Kivy Tutorial we are going to learn about Kivy ToggleButton, according to Kivy Documentation the ToggleButton widget acts like a checkbox. When you touch or click it, the state toggles between ‘normal’ and ‘down’ (as opposed to a Button that is only ‘down’ as long as it is pressed). toggle buttons can also be grouped to make radio buttons – only one button in a group can be in a ‘down’ state. the group name can be a string or any other hashable Python object.
We are going to create two files the first one is our Python file and the second file is our Kivy file, so first let’s create our Python file, and we want to add the following codes in that file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
from kivy.app import App from kivy.uix.gridlayout import GridLayout class MyToggleButton(GridLayout): pass class ToggleWindow(App): def build(self): return MyToggleButton() if __name__ == "__main__": window = ToggleWindow() window.run() |
In the above code first we have created MyToggleButton class, this class extends from GridLayout, because we want to add our kivy toggle button in the GridLayout, and we are not going to do anything in this class, it is just an empty class. you need return this class in your main class.
This is our .kv file, and i have name the file togglewindow.kv, make sure that this name should be similar to the main class name, in my case it is ToggleWindow class. in the file we need to define some rules for the Kivy ToggleButton, you need to specify the number of columns for the GridLayout, also we have added a RelativeLayout and in the RelativeLayout we have added our two togglebutton.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#:kivy 1.10.0 <MyToggleButton>: cols:2 RelativeLayout: ToggleButton: size_hint: None,None size:0.25 * root.width, 0.25 * root.height pos:0.125 * root.width, 0.350 * root.height text:"GeeksCodersOne" RelativeLayout: ToggleButton: size_hint: None,None size:0.25 * root.width, 0.25 * root.height pos:0.125 * root.width, 0.350 * root.height text:"GeeksCodersTwo" |
Run the complete code and this is the result.
![Kivy Tutorial - Kivy ToggleButton](https://geekscoders.com/wp-content/uploads/2020/11/kivy-tutorial-kivy-toggle-button.jpg)