Python | Spinner widget in Kivy using .kv file
Last Updated :
26 Oct, 2021
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.
👉🏽 Kivy Tutorial – Learn Kivy with Examples.
Spinner widget :
To work with spinner you must have to import:
from kivy.uix.spinner import Spinner
Spinner is a widget that provides a quick way to select one value from a set. In the default state, a spinner shows its currently selected value. Touching the spinner displays a dropdown menu with all the other available values from which the user can select a new one.
Like a combo box, a spinner object can have multiple values and one of the values can be selected.
A callback can be attached to the spinner object to receive notifications on selection of a value from the spinner object.
Basic Approach:
1) import kivy
2) import kivyApp
3) import spinner
4) import Floatlayout(according to need)
5) import window(optional)
6) Set minimum version(optional)
7) Create Layout class:
define the clicked function in it
8) Create App class
9) create .kv file (name same as the app class):
1) create Spinner
2) create callback
3) And many more styling as needed
10) return Layout/widget/Class(according to requirement)
11) Run an instance of the class
Below is the implementation :
In the below code we have created the spinner and done the sizing and positioning and also attached the callback to the values.
.py file:
Python3
from kivy.config import Config
Config. set ( 'graphics' , 'resizable' , True )
import kivy
from kivy.app import App
kivy.require( '1.9.0' )
from kivy.uix.spinner import Spinner
from kivy.uix.floatlayout import FloatLayout
from kivy.core.window import Window
class SampBoxLayout(FloatLayout):
def spinner_clicked( self , value):
print ( "Language selected is " + value)
class SampleApp(App):
def build( self ):
Window.clearcolor = ( 0.555 , 0.261 , . 888 , 0.5 )
return SampBoxLayout()
root = SampleApp()
root.run()
|
.kv file of the code:
Python3
<SampBoxLayout>:
Spinner:
id : spinner_id
on_text: root.spinner_clicked(spinner_id.text)
text: "Python"
values: [ "Python" , "Java" , "C++" , "C" , "C#" , "PHP" ]
size_hint: None , None
size: 200 , 50
pos_hint:{ 'center_x' :. 5 , 'top' : 1 }
|
Output:
Image 1:
Image 2:
Image 3:
Below is the output in video to get better understanding:
Share your thoughts in the comments
Please Login to comment...