DEV Community

Blackmare01wolf
Blackmare01wolf

Posted on • Edited on

Getting Started with kivy: What It Is and How It's Used

Introduction

If you want to build modern and interactive graphical user interfaces (GUI) for Python applications, Kivy is a great choice. Unlike Tkinter, Kivy is designed for multi-touch applications and works across multiple platforms, including Windows, macOS, Linux, iOS, and Android.

What is Kivy?

Kivy is an open-source Python framework for building multi-touch applications with a focus on usability and scalability. It is widely used for mobile and desktop applications due to its flexibility and customizable UI elements.

Setting Up Kivy

To install Kivy, run the following command:

pip install kivy
Enter fullscreen mode Exit fullscreen mode

Creating a Simple Kivy App

Below is an example of a basic Kivy application that includes a Label, TextInput (Entry), and Button, along with setting the window size and title.

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.core.window import Window

class MyApp(App):
    def build(self):
        Window.size = (400, 300)
        Window.title = "Kivy Example"

        layout = BoxLayout(orientation='vertical', padding=10, spacing=10)

        self.label = Label(text="Enter Your Name:")
        self.text_input = TextInput(multiline=False)
        self.button = Button(text="Submit", on_press=self.display_name)

        layout.add_widget(self.label)
        layout.add_widget(self.text_input)
        layout.add_widget(self.button)

        return layout

    def display_name(self, instance):
        self.label.text = f"Hello, {self.text_input.text}!"

if __name__ == "__main__":
    MyApp().run()
Enter fullscreen mode Exit fullscreen mode

Explanation of the Code

  1. Importing Kivy Modules:

    • App: The main application class.
    • Label, TextInput, Button, BoxLayout: UI elements used in the app.
    • Window: Used to set the size and title of the application.
  2. Setting Window Properties:

    • Window.size = (400, 300): Sets the window dimensions.
    • Window.title = "Kivy Example": Sets the title of the window.
  3. Creating a Layout:

    • BoxLayout arranges widgets vertically with spacing and padding.
  4. Adding Widgets:

    • Label: Displays text.
    • TextInput: Allows user input.
    • Button: Executes an action when clicked.
  5. Handling Button Clicks:

    • The display_name function updates the label with the entered text when the button is pressed.

Conclusion

Kivy is a powerful alternative to Tkinter for building cross-platform GUI applications. With features like multi-touch support and modern UI components, it is ideal for both desktop and mobile apps. Try creating your first Kivy app and explore its capabilities further!

If you want anything to know in this, comment , subscribe and follow me

Top comments (0)