Python | Button Action in Kivy
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 Desktop applications.
???????? Kivy Tutorial – Learn Kivy with Examples.
Now in this article, we will learn how to build a button in kivy by using the kv file, just like the button we use in calculators and many more places.
Buttons :
The Button is a Label with associated actions that are triggered when the button is pressed (or released after a click/touch). To bind the action of button when it pressed we have the function on_press.
Basic Approach for the button Actions using .kv file:
1) Import kivy
2) Import kivy app
3) Import Box layout
4) create .kv with label and button
5) Bind button to a method
6) create method
Now let’s code the .py file.
Python3
import kivy
kivy.require( "1.9.1" )
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
class RootWidget(BoxLayout):
def btn_clk( self ):
self .lbl.text = "You have been pressed"
class ActionApp(App):
def build( self ):
return RootWidget()
myApp = ActionApp()
myApp.run()
|
.kv file of the above code [action.kv] :
Must be saved with the name of the ActionApp class. i.e action.kv.
Python3
<RootWidget>:
lbl:my_label
BoxLayout:
orientation: 'vertical'
size: [ 1 , . 25 ]
Button:
text: 'Click Me'
font_size: "50sp"
color: [ 0 , 255 , 255 , . 67 ]
on_press: root.btn_clk()
Label:
id : my_label
text: 'No click Yet'
color: [ 0 , 84 , 80 , 19 ]
|
Output:
Video explaining output:
Note: BoxLayout arranges widgets in either in a vertical fashion that is one on top of another or in a horizontal fashion that is one after another.
Last Updated :
29 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...