Python - Button Action in Kivy


Kivy is an open source Python library for rapid development of applications that make use of innovative user interfaces, such as multi-touch apps. It is used to develop the Android application, as well as Desktops applications. In this article we will see how to use events when a button is pressed.

In the below example we have created a button and a label in a horizontal BoxLayout. We give initial text to the button and label. Then we create an event for clicking the button which changes the text both in the button and in the label. It is a single python file.

Example

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
class ButtonPressApp(App):
   def __init__(self):
      super(ButtonPressApp, self).__init__()
      self.btn = Button(text='Submit Button')
      self.lbl = Label(text='Some text here.')
   def build(self):
      self.btn.bind(on_press=self.click_event)
      layout = BoxLayout()
      layout.orientation = 'horizontal'
      layout.add_widget(self.btn)
      layout.add_widget(self.lbl)
      return layout
   def click_event(self, obj):
      self.btn.background_normal=''
      self.btn.color=(1,0,0,0.8)
      self.btn.text = 'Button Pressed'
      self.lbl.text = 'Text Changed'
MainLayout = ButtonPressApp()
MainLayout.run()

Running the above code gives us the following result −

Output

Before pressing the button.

After pressing the button.

Updated on: 28-Dec-2020

413 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements