Implementing Kivy GUI in Python

 

Why Kivy?

Of course, anyone who is familiar with several GUI frameworks may ask this question. What makes Kivy unique, then? Well, it does have a cause!

First, we should think about performance, flexibility, and worry separation (SoC). For crucial tasks, Kivy allows GPU acceleration and C-level execution. Because it works with touch devices and all the main operating systems, it is cross-platform. I'd advise looking up more details regarding Kivy's architecture rather than adding more theory here. In contrast, I'll get right into creating a straightforward Kivy Tic-Tac-Toe gaming application, which will cover numerous development-related topics.

Instalation 

The Kivy programme is incredibly straightforward to set up and use. You can choose any suitable installation method outlined in Installing Kivy based on your development environment, even if it depends on it.

You will discover how to write and run a Kivy programme in this section, as well as how to construct a simple Kivy interface.

Kivy GUI

Let's start by making a.py extension file. The Kivy app module must first be imported into our software in order to generate a Kivy interface.

The Kivy app module must first be imported into our software in order to generate a Kivy interface.

from kivy.app import App

Importing the label from kivy.uix.label at this time:

from kivy.uix.label import Label

Now is the time to write our main programme.

class HelloThere(App):
   
    def build(self):

        return Label(text="Hello Kivy!")

A class is inherited from the App class in the excerpt above. The build() function must then return a widget in order to build the application. We have returned a label with the word "Hello Kivy" in the code above.

Calling this function comes last. You have two options: either make an instance of the class or just write the following:

HelloThere().run()

The complete Python file appears as follows:

from kivy.app import App
from kivy.uix.label import Label

class HelloThere(App):
   
    def build(self):

        return Label(text="Hello Kivy!")
   

HelloThere().run()

This code's output will look like this:

Congratulations! Your initial Kivy app is successfully launched.

Kivy Button

This part will teach you how to construct buttons, alter their colours, enable and disable them, add images to them, and adjust their sizes and positions.
The label was used in the previous programme. Instead of importing a label to build a button, do the following:

first we need to import Label
from kivy.uix.button import Button

and instead of returning Label we will return Button. 
 return Button(text="Welcome to Kivy!")

The complete output screen will look like this: 















Don't worry if the button overflows the window; we'll resize it afterwards.

Change the colour of Kivy button

A Kivy button's standard colour is grey. By modifying the background color property in the format, you can alter the colour (r, g, b, a). The following code example:

from kivy.app import App

from kivy.uix.button import Button

class KivyButton(App):

    def build(self):

        return Button(text="Welcome to Kivy!", background_color=(155,0,51,53))

KivyButton().run()

When you run the program, it will show the button like this:











Change the size and position

You may quickly alter the location and size of a button using the button widget's pos and size hint properties. A Kivy button's size and position can be adjusted as follows:

from kivy.app import App

from kivy.uix.button import Button


class KivyButton(App):

    def build(self):

        return Button(text="Welcome to LikeGeeks!", pos=(300, 350), size_hint=(.25, .18))


KivyButton().run()

The following output will be like this:











While the size hint option indicates the button's size, the pos parameter specifies the button's position.


Image in Kivy Button

You will discover how to affix a picture to a button in this part. Instead of instantiating our widgets from code, we will be using the Kv language for the first time.

The Kivy libraries that we'll import are listed below:
from kivy.app import App

from kivy.uix.boxlayout import BoxLayout

from kivy.lang import Builder

The widgets are positioned using BoxLayout to allow for structured grouping of widgets. In Kivy, a variety of layouts, such as box layout, anchor layout, float layout, etc., can be used to arrange the widgets.

Load Kivy file

By default, Kivy tries to load a Kv file with your class's name, but without the word "App" and in lower case.
If your class is called TestApp, it will look in the same directory for a KV file with the name test.kv in order to load widgets from it.
The Kivy Builder is a different method for loading the kv file.

Widgets can be loaded from Kv strings or files using Kivy Builder. For instance, you may use the widget builder as follows to construct a widget:
Builder.load_string(""" """)

The necessary widgets are added inside the triple quotation marks, along with their properties. Below is an example that includes the KivyButton class.

The button's text and size are set first, and then the source attribute and image coordinates are used to provide the picture.

Since the image is in the same directory, the image path is now valid.

Builder.load_string("""

<KivyButton>:

    Button:

        text: "Hello Button!"

        size_hint: .12, .12

        Image:

            source: 'images.jpg'

            center_x: self.parent.center_x

            center_y: self.parent.center_y  
   
""")

Let's import this definition and execute our class right away:

from kivy.app import App

from kivy.uix.boxlayout import BoxLayout

from kivy.lang import Builder

Builder.load_string("""

<KivyButton>:

    Button:

        text: "Hello Button!"

        size_hint: .12, .12

        Image:

            source: 'images.jpg'

            center_x: self.parent.center_x

            center_y: self.parent.center_y  
   
""")


class KivyButton(App, BoxLayout):

    def build(self):

        return self


KivyButton().run()


EventDispatcher

The Kivy Framework's primary base class is EventDispatcher. It is in charge of dispatching and registering occurrences. EventDispatcher classes include those like Widget, Animation, and Clock, for instance. There are three types of events on Kivy, including:

Clock Events

The kivy.clock is connected to these occurrences. class time. By using its methods, such as Clock.schedule once, Clock.schedule interval, and Clock.create trigger, you can register or schedule trigger events. For instance,
from kivy.clock import Clock  

def callback_function(duration):
   pass

# Schedule callback_function for every 2 seconds
event = Clock.schedule_interval(callback_function, 2)

# Canceling the event
event.cancel()

# Unscheduling the event using Clock.unschedule
Clock.unschedule(event)

# Schedule callback_function in 3 seconds
Clock.schedule_once(callback_function, 3)

# Create a trigger to callback_function with a delay of 5 seconds.
event_trigger = Clock.create_trigger(callback_function, 5)

# Execute the trigger
event_trigger()


Widget Events

The widget can support two different types of events, such as

1. Property events: Every widget comes with a set of default properties, including size and position. An event is triggered each time its value changes. More on the properties classes will be covered in the following section.

2. Predefined events are those that are connected to user actions, such as when a button is pressed or released.


Custom Events

The EventDispatcher class enables us to create our own event dispatchers.

Properties

The property classes that Kivy implements are constructed using the Observer pattern. There are several different property classifications, including

  • StringProperty
  • NumericProperty
  • BoundedNumericProperty
  • ObjectProperty
  • DictProperty
  • ListProperty
  • OptionProperty
  • AliasProperty
  • BooleanProperty
  • ReferenceListProperty


reserved keywords

Each widget has its own set of predefined properties. Using the following reserved keywords, Kivy provides a scope of context to access these characteristics.

self

self keyword refers to the current widget context. For example,
BoxLayout:
   orientation:'vertical'
   Button:
       text: self.state and ('UP' if self.state == 'normal' else 'DOWN')

root

The root widget context is referenced by the root keyword. This gives you access to characteristics at the root level. For instance,
<MyCustomeWidget@BoxLayout>:
   custome_text: 'Custom text'
   orientation:'vertical'
   Button:
       text: root.custom_text

app

App instance specified in main.py is referenced by the term "app," such as

from kivy.app import App
from kivy.uix.button import Button

class MyApp(App):
    title = 'My Kivy application'

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

You can use the app instance described below in the KV file.

BoxLayout:
   orientation:'vertical'
   Label:
       text: app.title

You can use this kivy.app if you wish to access the app instance from anywhere in your Python context. App.get running app(). The app instance that is presently running will be returned.

args

The on <action> callback methods' parameters can be accessed by using the args keyword. For instance,
#: import BooleanProperty kivy.properties.BooleanProperty

BoxLayout:

   focus_status: BooleanProperty(False)

   orientation:'vertical'

   TextInput:

       on_focus: root.focus_status = args[1]

   Label:

       text: "Text Input has focus %s " % str(root.focus_status)

Here, the received method arguments were placed in a BooleanProperty variable using the on action method. In later parts, I'll expand on properties.


Ids

The id attribute will always be available on the weakref to the widget rather than the widget instance when it is defined in a KV file. When a KV file is processed, the root widget's dictionary's "ids" value is updated to include the weekrefs of all widgets having the id attribute. Here is an illustration using the above.
BoxLayout:
   orientation:'vertical'
   Button:
       id: btn
       text: "Press me"
   Label:
       text: "Button state is %s " % root.ids.btn.state


After reading this article you can go to check out the tutorial video I did about Kivy from installing it to implementing it. 

Youtube video link: click here


Comments

Popular Posts