In this Kivy Tutorial we want to learn that How to Create DropDown in Python Kivy, so Python Kivy is an open source GUI framework for Python Programming Language, that you can use it for building multi touch applications for different platforms like desktops, mobile devices and Raspberry Pi. Kivy DropDown is a list of options that can be selected by clicking or tapping on a button, in this article we want to talk that how to create dropdowns in Python Kivy.
First of all we need to import required modules from Kivy.
1 2 3 |
from kivy.app import App from kivy.uix.button import Button from kivy.uix.dropdown import DropDown |
After that we have imported the necessary libraries, we can create a dropdown by instantiating DropDown class.
1 |
dropdown = DropDown() |
For adding options to the dropdown, we need to create buttons for each option and add them to the dropdown, in this code we are going to loop through list of the options, after that we set the text of each button and also we set the size_hint.
1 2 3 4 |
for option in ['Codeloop.org', 'Python', 'Java']: btn = Button(text=option, size_hint_y=None, height=44) btn.bind(on_release=lambda btn: dropdown.select(btn.text)) dropdown.add_widget(btn) |
Now that we have created the dropdown and added options to it, we need to add it to our Kivy app.
1 2 3 4 5 6 |
class MyApp(App): def build(self): main_button = Button(text='Click me', size_hint=(None, None)) main_button.bind(on_release=dropdown.open) dropdown.bind(on_select=lambda instance, x: setattr(main_button, 'text', x)) return main_button |
At the end we can run our app, for running our app we need to create an instance of our MyApp class and call the run() method.
1 2 |
if __name__ == '__main__': MyApp().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 27 28 29 30 |
from kivy.app import App from kivy.uix.button import Button from kivy.uix.dropdown import DropDown class MyApp(App): def build(self): # Create an instance of DropDown dropdown = DropDown() # Create button for each option for option in ['Codeloop', 'Python', 'Java']: # Create a button with specific size btn = Button(text=option, size_hint_y=None, height=44) # Bind the button to select the text when released btn.bind(on_release=lambda btn: dropdown.select(btn.text)) dropdown.add_widget(btn) # Create main button that will trigger the dropdown main_button = Button(text='Click me', size_hint=(None, None)) main_button.bind(on_release=dropdown.open) # Bind the main button to open the dropdown when clicked # Bind dropdown's select event to change dropdown.bind(on_select=lambda instance, x: setattr(main_button, 'text', x)) # Return the main button as the root widget return main_button if __name__ == '__main__': MyApp().run() # Run the Kivy app |
Run the complete code and this will be the result
Subscribe and Get Free Video Courses & Articles in your Email