Python > GUI Programming with Python > Kivy > Widgets and Layouts

Basic Kivy Layout and Widgets

This snippet demonstrates a basic Kivy application showcasing different widgets arranged using a BoxLayout. It includes a Label, a Button, and a TextInput field, demonstrating how to structure a simple GUI with Kivy.

Code

import kivy imports the core Kivy library. from kivy.app import App imports the base class for creating Kivy applications. from kivy.uix.label import Label imports the Label widget for displaying text. from kivy.uix.gridlayout import GridLayout imports the GridLayout for arranging widgets in a grid. from kivy.uix.textinput import TextInput imports the TextInput widget for accepting user input. from kivy.uix.button import Button imports the Button widget for user interaction. from kivy.uix.boxlayout import BoxLayout imports the BoxLayout for arranging widgets in a horizontal or vertical box. The MyGridLayout class inherits from GridLayout and defines the layout of the application. It contains TextInput fields for name, pizza, and color, and a submit button. The MyApp class inherits from App and defines the application. The build method returns the root widget, which is an instance of MyGridLayout. The press method is called when the submit button is pressed. It retrieves the text from the TextInput fields, prints a message to the console, and clears the TextInput fields. The kivy.require('2.0.0') line specifies the minimum Kivy version required to run the application. The if __name__ == '__main__': block ensures that the application is only run when the script is executed directly, not when it is imported as a module.

import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout


kivy.require('2.0.0')

class MyGridLayout(GridLayout):
    # Initialize infinite keywords to args
    def __init__(self,  kwargs):
        # Execute GridLayout constructor
        super(MyGridLayout, self).__init__()

        # Set columns
        self.cols = 1
        self.row_force_default=True
        self.row_default_height=40


        # Create top_grid layout
        self.top_grid = GridLayout(
            row_force_default=True,
            row_default_height=40,
            cols = 2
        )

        # Add widgets
        self.top_grid.add_widget(Label(text="Name: "))
        self.name = TextInput(multiline=False)
        self.top_grid.add_widget(self.name)

        self.top_grid.add_widget(Label(text="Favorite Pizza: "))
        self.pizza = TextInput(multiline=False)
        self.top_grid.add_widget(self.pizza)

        self.top_grid.add_widget(Label(text="Favorite Color: "))
        self.color = TextInput(multiline=False)
        self.top_grid.add_widget(self.color)

        # Add the top grid to the layout
        self.add_widget(self.top_grid)

        # Create a Submit Button
        self.submit = Button(text="Submit", font_size=32)

        # Bind the button
        self.submit.bind(on_press=self.press)
        self.add_widget(self.submit)

    def press(self, instance):
        name = self.name.text
        pizza = self.pizza.text
        color = self.color.text

        # Print to the app!
        #self.add_widget(Label(text=f"Hello {name}, you like {pizza} pizza, and your favorite color is {color}!" ))
        print(f"Hello {name}, you like {pizza} pizza, and your favorite color is {color}!")

        # Clear the input boxes
        self.name.text = ""
        self.pizza.text = ""
        self.color.text = ""


class MyApp(App):
    def build(self):
        return MyGridLayout()


if __name__ == '__main__':
    MyApp().run()

Concepts Behind the Snippet

This snippet uses fundamental Kivy concepts:

  • Widgets: The basic building blocks of the UI (Label, Button, TextInput).
  • Layouts: Containers that manage the size and position of widgets (GridLayout).
  • App Class: The main application class responsible for building and running the Kivy app.
  • Event Handling: The on_press event of the Button is bound to a method (press) that gets executed when the button is clicked.

Real-Life Use Case

This example can be extended to create more complex forms for data input, such as registration forms, settings panels, or simple data entry applications. The input fields can be connected to data models or databases to store the information entered by the user.

Best Practices

  • Separate UI and Logic: For larger applications, separate the UI definition from the application logic for better maintainability. This can be achieved using Kivy's KV language.
  • Use KV Language: Define the UI in a separate .kv file for better organization and readability.
  • Error Handling: Implement error handling to gracefully handle unexpected inputs or errors during runtime.

When to Use Them

  • Simple GUIs: Use BoxLayout and other layouts for creating simple and straightforward GUIs.
  • Data Entry Forms: TextInput widgets are suitable for creating forms for users to enter data.
  • Interactive Elements: Buttons provide interactive elements that trigger actions when clicked.

Alternatives

Other layout options include:

  • FloatLayout: Allows widgets to be positioned using absolute coordinates.
  • RelativeLayout: Positions widgets relative to other widgets or the layout itself.
  • StackLayout: Arranges widgets in a stack (horizontally or vertically).

Pros

  • Cross-platform compatibility.
  • Easy to learn and use for simple GUIs.
  • Flexible layout options.

Cons

  • Can become complex for large, intricate UIs.
  • Performance can be a concern for very demanding applications.

FAQ

  • How do I change the color of a button?

    You can change the color of a button by setting the background_color property. For example: Button(text='Click Me', background_color=(1, 0, 0, 1)) (red).
  • How do I make the text bigger?

    You can change the font size of a widget by setting the font_size property. For example: Label(text='Hello', font_size=32).