In this Python Kivy article we want to learn How to Create CheckBox in Python Kivy, so Kivy is powerful framework for creating graphical user interfaces (GUIs) in Python. and one of the best features of Kivy is the ability to create interactive elements such as checkboxes.
First of all we need to install Python Kivy and you can use pip command for that.
1 |
pip install kivy |
For creating Kivy CheckBox first we need to import our required modules from Kivy like CheckBox, BoxLayout and App.
1 2 3 |
from kivy.uix.checkbox import CheckBox from kivy.app import App from kivy.uix.boxlayout import BoxLayout |
Now that we have imported the necessary modules, we can create our checkbox. we want to create a simple checkbox that displays the text Check me and is unchecked by default.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
def build(self): # Create box layout layout = BoxLayout() # Create checkbox checkbox = CheckBox(active=False, size_hint=(None, None), size=(50, 50), pos=(100, 100)) checkbox_label = Label(text="Check me!", size_hint=(None, None), size=(100, 50), pos=(170, 100)) # Add checkbox to layout layout.add_widget(checkbox) layout.add_widget(checkbox_label) return layout |
In the above code we have created a BoxLayout widget and CheckBox widget. also we are setting the active attribute of the checkbox to False, which means that it will be unchecked by default. we are also setting the size_hint attribute to None, and finally, we are setting the pos attribute which will position the checkbox at specific pixels on the screen.
we are also creating a Label widget and setting its size_hint attribute to None, and finally, we are adding both the checkbox and the label to the BoxLayout widget using add_widget method, and returning the layout from the build method.
And at the end we need to run Python Kivy application
1 2 3 |
if __name__ == '__main__': app = CheckBoxApp() app.run() |
This is the complete code for this article
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
from kivy.uix.checkbox import CheckBox from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label class CheckBoxApp(App): def build(self): # Create box layout layout = BoxLayout() # Create checkbox checkbox = CheckBox(active=False, size_hint=(None, None), size=(50, 50), pos=(100, 100)) checkbox_label = Label(text="Check me", size_hint=(None, None), size=(100, 50), pos=(170, 100)) # Add checkbox to the layout layout.add_widget(checkbox) layout.add_widget(checkbox_label) return layout if __name__ == '__main__': app = CheckBoxApp() app.run() |
Run the code and this will be the output
