In this Kivy Tutorial we want to learn about How to Create Spinner in Python Kivy, so Kivy is an open source Python library for creating graphical user interfaces or GUIs that are cross platform and can run on different operating systems such as Windows, macOS and Linux, and spinners allows users to select an item from a list.
First of all we need to install Kivy, you can use pip for the installation, open your command prompt or terminal and write this command.
1 |
pip install kivy |
After installation, we need to import the necessary modules for creating the spinner. in this example we are using Kivy App class and Kivy Spinner class.
1 2 3 |
import kivy from kivy.app import App from kivy.uix.spinner import Spinner |
Now we need to create a class for our spinner. this class will inherit from the Kivy App class, and it provides a base class for creating Kivy applications. inside this class, we want to create an instance of the Kivy Spinner class, and it is used to create our spinner.
1 2 3 4 |
class SpinnerApp(App): def build(self): spinner = Spinner(text='Select One', values=('Option 1', 'Option 2', 'Option 3')) return spinner |
Now that we have created our SpinnerApp class, we can run the application by adding the following code to our Python file.
1 2 |
if __name__ == '__main__': SpinnerApp().run() |
We can also customize the appearance and behavior of the spinner by setting different attributes of the Spinner class. for example, we can set the size of the spinner by setting size_hint attribute, and we can set the height of the dropdown list by setting the dropdown_height attribute.
1 2 3 4 |
class SpinnerApp(App): def build(self): spinner = Spinner(text='Select One', values=('Option 1', 'Option 2', 'Option 3'), size_hint=(0.3, 0.1), dropdown_height=100) return spinner |
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 |
from kivy.app import App # Import the Spinner class from kivy.uix.spinner import Spinner class SpinnerApp(App): # Override the build method def build(self): spinner = Spinner( text='Select One', # Default text shown on the spinner values=('Option 1', 'Option 2', 'Option 3'), # Options available in the dropdown menu size_hint=(None, None), # Disable size hinting to use fixed size size=(200, 50) # Set width to 200 pixels and height to 50 pixels ) # Return the spinner widget return spinner if __name__ == '__main__': # Run the Kivy application SpinnerApp().run() |
Run the code and this will be the result
Subscribe and Get Free Video Courses & Articles in your Email