Kivy – Bezier

Kivy – Bezier ”; Previous Next In this chapter, we shall create a Kivy app that will interactively draw a Bezier line along the list of points. If a closed line is drawn making use of the x and y coordinates computed with the help of following code segment, the resulting figure resembles a Pacman character − from math import cos, sin, radians x = y = 300 z = 200 self.points = [x, y] for i in range(45, 360, 45): i = radians(i) self.points.extend([x + cos(i) * z, y + sin(i) * z]) with self.layout.canvas: Color(1.0, 0.0, 1.0) self.line = Line( points=self.points + self.points[:2], dash_offset=10, dash_length=100 ) It generates a line pattern as the following − Then, we draw a Bezier line making use of the same list of points. Color(1.0, 0.0, 1.0) self.line = Line( points=self.points + self.points[:2], dash_offset=0, dash_length=100 ) The Line as well as the Beizer will appear as this − Now we want to construct these two curves dynamically. We use two slidersto change the dash length and offset values of both the line instruction and Bezier instruction as the value property of each slider changes with the following event handlers − def _set_bezier_dash_offset(self, instance, value): # effect to reduce length while increase offset self.bezier.dash_length = 100 – value self.bezier.dash_offset = value def _set_line_dash_offset(self, instance, value): # effect to reduce length while increase offset self.line.dash_length = 100 – value self.line.dash_offset = value As a result, change the slider values to see how the two curves are redrawn dynamically. Example The complete code is given below − from kivy.app import App from kivy.uix.floatlayout import FloatLayout from kivy.uix.label import Label from kivy.uix.slider import Slider from kivy.graphics import Color, Bezier, Line from kivy.core.window import Window Window.size = (720,400) class Main(App): title=”Bezier Example” def _set_bezier_dash_offset(self, instance, value): # effect to reduce length while increase offset self.bezier.dash_length = 100 – value self.bezier.dash_offset = value def _set_line_dash_offset(self, instance, value): # effect to reduce length while increase offset self.line.dash_length = 100 – value self.line.dash_offset = value def build(self): from math import cos, sin, radians x = y = 300 z = 200 # Pacman ! self.points = [x, y] for i in range(45, 360, 45): i = radians(i) self.points.extend([x + cos(i) * z, y + sin(i) * z]) print (self.points) self.layout = FloatLayout() with self.layout.canvas: Color(1.0, 0.0, 0.0) self.bezier = Bezier( points=self.points, segments=150, loop=True, dash_length=100, dash_offset=10 ) Color(1.0, 0.0, 1.0) self.line = Line( points=self.points + self.points[:2], dash_offset=10, dash_length=100) l1=Label( text=”Beizer offset”, pos_hint={”x”:.1}, size_hint=(.1, None), height=50 ) self.layout.add_widget(l1) s1 = Slider( y=0, pos_hint={”x”: .3}, size_hint=(.7, None), height=50 ) self.layout.add_widget(s1) s1.bind(value=self._set_bezier_dash_offset) l2=Label( text=”Line offset”, y=50, pos_hint={”x”:.1}, size_hint=(.1, None), height=50 ) self.layout.add_widget(l2) s2 = Slider( y=50, pos_hint={”x”: .3}, size_hint=(.7, None), height=50 ) self.layout.add_widget(s2) s2.bind(value=self._set_line_dash_offset) return self.layout if __name__ == ”__main__”: Main().run() Output The following screenshots show the curves at two different slider positions − Print Page Previous Next Advertisements ”;

Kivy – Miscellaneous

Kivy – Miscellaneous ”; Previous Next Kivy – Exception Handling In programming, Exception handling refers to the mechanism to prevent the program from crashing if it encounters run-time errors. Kivy provides a class called ExceptionHandler that can manage exceptions raised by Kivy or by your own code. The ExceptionManager class is defined in the “kivy.base” module. You need to import it from “kivy.base” and access the instance that handles Kivy exceptions. You can use this class to add custom handlers for different types of exceptions, or to override the default behavior of Kivy when an exception occurs. For example, you can use the handle_exception method to log the exception, show a message to the user, or exit the app gracefully. from kivy.base import ExceptionHandler, ExceptionManager from logging import Logger class handler(ExceptionHandler): def handle_exception(self, inst): Logger.exception(”Exception caught by ExceptionHandler”) return ExceptionManager.PASS ExceptionManager.add_handler(handler()) A handler function that takes the exception as an argument and returns one of the following values − ExceptionManager.PASS − The exception should be ignored as it was handled by the handler. ExceptionManager.RAISE − The exception should be re-raised. ExceptionManager.USER_HANDLED − The exception was handled by the user and should not be logged. You can also use the handle_exception method to manually handle an exception using the registered handlers. Kivy – Resources Management The “kivy.resources” module includes the functionality to for searching for specific resources across a list of paths particularly if you application deals with multiple paths and projects. When Kivy looks for any resource such as an image file, or a “kv” file, it searches through a predetermined set of folders. You can modify this folder list using the resource_add_path() and resource_remove_path() functions. If you want to use any alternative for the default style.kv or data/defaulttheme0.png you can add the path to your preferred alternatives via the resource_add_path() method. Following functions are defined in the “kivy.resources” module − resource_add_path(path) − Add a custom path to search in. resource_find(filename, use_cache=False) − Search for a resource in the list of paths. Find results are cached for 60 seconds. This can be disabled using use_cache=False. resource_remove_path(path) − Remove a search path. Kivy – Weak Proxy Python uses reference counting algorithm for garbage collection, by keeping count of how many objects are referencing a certain object. If the garbage collector finds that an object is referenced by another object, it can”t be garbage collected. If the counter reaches zero, the garbage collector will free that object. A weak reference is a reference that does not protect the object from getting garbage collected. To create weak references, Python has provided us with a module named weakref. Kivy defines WeakProxy class in kivy.weakproxy module. In order to allow garbage collection, the WeakProxy class provides weak references to objects. It effectively enhances the weakref.proxy by adding comparison support. Kivy – Context The Kivy objects Clock, Cache and Builder are global objects. To use them in the context of the present application you will have to register it. The kivy.context module defines a Context class, which inherits the properties of Python”s built-in dict class. In addition to the dict methods, we have the following functions defined in this module − get_current_context() − Return the current context. egister_context(name, cls, *args, **kwargs) − Register a new context. Print Page Previous Next Advertisements ”;

Kivy – App Life Cycle

Kivy – App Life Cycle ”; Previous Next A Kivy app goes through various stages from the time it is executed and it stops. The following diagram shows the different stages − Let us now have a detailed discussion about each of these stages − Initialize UI The App class in the Kivy framework is the one that represents a Kivy application. Creating an App object is the first step in the app”s life cycle. from kivy.app import App Declare a subclass of App class, and override build() method. from kivy.app import App class MyApp(App): def build(self): #UI Design It in builds the application”s UI by either calling the build() method or with the help of the “.kv” file. If required, the app”s configurations are loaded from the respective “.ini” file. Event Loop Once the user interface is loaded, the App object enters in an infinite event loop. if __name__ == ”__main__”: MyApp().run() Various widgets assembled in the interface now absorb the user interactions such as button click or text input, and respond according to corresponding event handlers. In response to the user interaction, the state of any widget or app may be modified. To run the application, execute the following command from the OS terminal − Python MyApp.py While you can run your Kivy app this way on Windows or Linux, you may have to take some additional steps for running it on Android. For Android, you should build an APK (Android Package Kit). You should use Buildozer, a tool that automates the entire build process. It installs all the prerequisites for python-for-android, including the android SDK and NDK, then builds an APK that can be automatically pushed to the device. Buildozer currently works only in Linux and macOS (for Windows, activate WSL on the machine and then use Buildozer from within WSL) Pause / Resume While the app is running, it can be made to pause. For example, if the application window is minimized, or the device itself goes in sleep mode, the pause mode helps in conserving the resources. Kivy has an on_pause() Event handler. It is called when Pause mode is requested. You should return True if your app can go into Pause mode, otherwise return False and your application will be stopped. You cannot control when the application is going to go into this mode. It”s determined by the Operating System and mostly used for mobile devices (Android/iOS) and for resizing. The app can resume running from the point at which it was paused. Kivy”s on_resume() Event handler gets called when your application is resuming from the Pause mode. When resuming, the OpenGL Context might have been damaged / freed. This is where you can reconstruct some of your OpenGL state. Stop It is when the user closes the app by invoking an appropriate method in the app”s code. All the cleanup action is undertaken before the termination of application”s run. Print Page Previous Next Advertisements ”;

Kivy – Events

Kivy – Events ”; Previous Next Kivy is a Python library that helps you to build cross-platform GUI applications. Any GUI application is event driven, wherein the flow of the program is not sequential (top to bottom), but is decided by the user interactions with the widgets on the interface. User actions such as clicking a button, “selecting an item from a list” or “choosing an option from available radio buttons”, etc. are called events. A GUI-based program anticipates all possible events that can occur in and around its environment and dispatch them to appropriate handler functions as and when (and if) a certain event occurs. When the run() method of Kivy”s App object is called, the application starts an “event listening” loop and triggers appropriate callback functions, one each for a type of event. Global Event Dispatcher The Kivy framework includes the EventDispatcher class. It dispatches the event object to the widget tree and the event is propagated through the widget hierarchy. When a widget that is in a position to process the event, its associated callback handler is triggered. The Widget, Animation and Clock classes are examples of event dispatchers. Clock is a global event dispatcher that allows you to schedule and trigger events at specific intervals. It defines methods such as ”schedule_once()” and ”schedule_interval()” to register functions or methods to be called after a certain delay or at regular intervals. This mechanism is useful for handling timed events, animation updates, and other recurring tasks in your app. Example In the following example, we have put a label and two buttons in the widget tree. The button captioned “Start” schedules an event to occur periodically after every one second. The schedule_interval() function is written with the following syntax − Clock.schedule_interval(callback, timeout) On the other hand, the second button captioned as “Stop” calls the unscheduled() method which removes the scheduled event. from kivy.app import App from kivy.uix.label import Label from kivy.uix.button import Button from kivy.uix.boxlayout import BoxLayout from kivy.clock import Clock from kivy.config import Config # Configuration Config.set(”graphics”, ”width”, ”720”) Config.set(”graphics”, ”height”, ”400”) Config.set(”graphics”, ”resizable”, ”1”) class DemoApp(App): def build(self): lo = BoxLayout(orientation=”vertical”) self.l1 = Label(text=”0″, font_size=100) self.b1 = Button(text=”start”, font_size=100, color=(0, 0, 1, 1)) self.b1.bind(on_press=self.onstart) self.b2 = Button(text=”Stop”, font_size=100, color=(1, 0, 0, 1)) self.b2.bind(on_press=self.onstop) lo.add_widget(self.l1) lo.add_widget(self.b1) lo.add_widget(self.b2) return lo def onstart(self, event): print(“started”) Clock.schedule_interval(self.update_label, 1) def onstop(self, event): Clock.unschedule(self.update_label) def update_label(self, event): self.l1.text = str(int(self.l1.text) + 1) if __name__ == ”__main__”: DemoApp().run() Output Run the above program. The label initially shows “0”. Click the Start button. The label starts incrementing the number on it with each second. Press the “Stop” button to unschedule the event. Widget Events Most of the widgets Kivy have built-in event handling capabilities. In fact, each widget is designed to handle specific type of events. For example, the Button widget handles the event caused by clicking it. You can register event handlers for specific events that occur on a widget, such as button clicks, touch events, or keyboard events. Usually, the event handlers are defined as methods in your widget”s class or App class. They generally are prefixed with ”on_” followed by the name of the event. For example, ”on_press” for a button press event. When an event occurs, Kivy automatically calls the corresponding event handler method, passing relevant information about the event as arguments. Inside the event handler, you can define the desired behavior or actions to perform. Events Associated with Widgets Given below is a list of the events associated with some of the most commonly used widgets − Button on_press − Triggered when the button is pressed. on_release − Triggered when the button is released. on_touch_down − Triggered when a touch event starts on the button. on_touch_up − Triggered when a touch event ends on the button. TextInput on_text_validate − Triggered when the user finishes editing the text input (by pressing Enter or Return). on_focus − Triggered when the text input receives or loses focus. on_text − Triggered whenever the text in the input field changes. CheckBox on_active − Triggered when the checkbox is checked or unchecked. Slider on_value − Triggered when the slider”s value changes. on_touch_down − Triggered when a touch event starts on the slider. on_touch_up − Triggered when a touch event ends on the slider. ToggleButton on_state − Triggered when the toggle button”s state changes (toggled on or off). on_press − Triggered when the toggle button is pressed. ListView on_select − Triggered when an item in the list view is selected. FileChooser on_selection − Triggered when a file or directory is selected in the file chooser. Switch on_active − Triggered when the switch is toggled on or off. Video on_load − Triggered when the video finishes loading. on_play − Triggered when the video starts playing. on_pause − Triggered when the video is paused. on_stop − Triggered when the video stops playing. Spinner on_text − Triggered when an item is selected from the spinner. ActionButton on_press − Triggered when the action button is pressed. Examples − Event Handling in Kivy These events will be discussed when we explain each of the widgets in Kivy framework. However, for this chapter, two examples of event handling are given here. Example 1 The first example shows the “on_press” event of a Button widget. In the code below, we have a Label and a Button widget, arranged in a BoxLayout. To process the on_press event, we bind the button with onstart() method defined in the DemoApp class

Kivy – Getting Started

Kivy – Getting Started ”; Previous Next Kivy is an open-source Python library. It allows you to build multi-touch applications with a natural user interface (NUI). With Kivy, you can develop cross-platform applications. The same code, written once, can be deployed on different various operating system platforms such as Windows, macOS, Linux, Android, and iOS. Popular GUI Frameworks in Python Kivy is one of the many GUI frameworks available in the Python ecosystem. Some of the popular Python libraries for building desktop GUI applications are − Tkinter − Tkinter package is bundled with Python”s standard library. It is the standard Python interface to the Tcl/Tk GUI toolkit. PyQt5 − This library is a Python port for the Qt GUI toolkit. Our extensive tutorial on PyQt5 can be accessed here. WxPython − WxPython library allows Python programmer to have access to WxWidgets, an open-source GUI toolkit, originally written in C++. To learn more about WxPython, click here. Kivy − Kivy is a Python library that helps you to build cross-platform GUI applications for Windows, Linux, iOS as well as Android. Kivy supports touch-enabled input. All the widgets in Kivy GUI framework have the capability to handle multi-touch gestures. Kivy is equipped with powerful graphics and multimedia features. A Kivy app can support audio, video, animations, 2D as well as 3D graphics. Key Features of Python Kivy Here are some key features of Python Kivy − Kivy supports touch-enabled input. All the widgets in Kivy GUI framework have capability to handle multi-touch gestures. Kivy”s comprehensive GUI widgets and robust layout management makes designing attractive interfaces easily possible. Kivy is equipped with powerful graphics and multimedia features. This makes it possible to incorporate, 2D as well as 3D graphics, animations, audio and video componenets in the application. Various types of input devices are supported by Kivy. It includes touch, mouse and gestures. Kivy API can access mobile device hardware components such as camera, GPS, etc. Kivy uses OpenGL ES 2 graphics library, and is based on Vertex Buffer Object and shaders. Kivy relies upon Cython for its core implementation, and SDL2 (Simple DirectMedia Layer) for low-level multimedia and input handling. To deploy the Kivy application on desktops with Windows, Linux or iOS operating systems, the distributable is built with PyInstaller. To build an APK for Android, you need to use Android Studio and Buildozer utility. The Kivy Language Kivy uses a special declarative language called Kivy Language (sometimes also called Kv language) to build user interface layouts for Kivy applications. It serves the purpose of separating the design aspect of an app from its programming logic. The design is written in a text file with “.kv” extension. Kivy framework automatically loads the “.kv” file and builds the UI based on the specifications given in it. The initial version of Kivy library was released in 2011. Currently, Kivy version 2.2 is available, which has been released in May 2023. Print Page Previous Next Advertisements ”;

Kivy – Architecture

Kivy – Architecture ”; Previous Next Read this chapter to understand the design architecture of Kivy framework. On one end, Kivy provides various widgets that lets the user to interact with the application, and on the other end, it interacts with the various hardware devices such as mouse TUIO, audio and video streams, etc. The middle layer consists of drivers or providers for processing touch inputs, audio and video, graphics instructions and text input. This is the official architectural diagram of the Kivy framework − Core Providers An important feature of Kivy architecture is “modularity” and “abstraction”. The actions such as opening a window, reading audio and video stream, loading images, etc., are the core tasks in any graphical application. Kivy abstracts these core tasks by providing easy to implement API to the drivers that control the hardware. Kivy uses specific providers for operating system on which your app is being run. Each operating system (Windows, Linux, MacOS, etc.) has its own native APIs for the different core tasks. The act as an intermediate communication layer between the operating system on one side and to Kivy on the other. Thus Kivy fully leverages the functionality exposed by the operating system to enhance the efficiency. Use of platform-specific libraries reduces the size of the Kivy distribution and makes packaging easier. This also makes it easier to port Kivy to other platforms. The Android port benefited greatly from this. Input Providers An input provider is a piece of code that adds support for a specific input device. The different input devices having built-in support in Kivy include − Android Joystick Input Provider Apple”s trackpads TUIO (Tangible User Interface Objects) mouse emulator HIDInput To add support for a new input device, provide a new class that reads your input data from your device and transforms them into Kivy basic events. Graphics OpenGL is base of the entire Graphics API of Kivy framework. OpenGL instructions are used by Kivy to issue hardware-accelerated drawing commands. Kivy does away the difficult part of writing OpenGL commands by defining simple-to-use functionality. Kivy uses OpenGL version 2.0 ES (GLES or OpenGL for embedded systems) with which you can undertake cross-platform development. Core Library The high level abstraction is provided by the following constituents of Kivy framework − Clock − the Clock API helps you to schedule timer events. Both one-shot timers and periodic timers are supported. Gesture Detection − An important requirement of multitouch interfaces. The gesture recognizer detects various kinds of strokes, such as circles or rectangles. You can even train it to detect your own strokes. Kivy Language − The kivy language is used to easily and efficiently describe user interfaces. This results in separation of the app design from developing the application logic. Properties − Kivy”s unique concept of property classes (they are different from property as in a Python class) are the ones that link your widget code with the user interface description. UIX Kivy”s user interface is built with widgets and layouts. Widgets are the UI elements that you add to your app to provide some kind of functionality. Examples of widget include buttons, sliders, lists and so on. Widgets receive MotionEvents. More than one widgets are arranged in suitable layouts. Kivy provides layout classes that satisfy the requirement of placement of widgets for every purpose. Examples would be Grid Layouts or Box Layouts. You can also nest layouts. Event Dispatch The term “widget” is used for UI elements in almost all graphics toolkits. Any object that receives input events is a widget. One or more widgets are arranged in a tree structure. The Kivy app window can hold only one root widget, but the root widget can include other widgets in a tree structure. As a result, there is a “parent-children-sibling” relationship amongst the widgets. Whenever a new input event occurs, the root widget of the widget tree first receives the event. Depending on the state of the touch, the event is propagated down the widget tree. Each widget in the tree can either process the event or pass it to the next widget in hierarchy. If a widget absorbs and process the event, it should return True so that its propagation down the tree is stopped and no further processing will happen with that event. def on_touch_down(self, touch): for child in self.children[:]: if child.dispatch(”on_touch_down”, touch): return True Since the event propagates through the widget tree, it is often necessary to verify if the event has occurred in the area of a certain widget that is expected to handle it. The collide_point() method can help in ascertaining this fact. This method checks if the touch position falls within the ”watched area” of a certain widget and returns True or False otherwise. By default, this checks the rectangular region on the screen that”s described by the widget”s pos (for position; x & y) and size (width & height). Print Page Previous Next Advertisements ”;

Kivy – Home

Kivy Tutorial PDF Version Quick Guide Resources Job Search Discussion Kivy is a Python library that helps you to build cross-platform GUI applications for Windows, Linux, iOS as well as Android. Kivy supports touch-enabled input. All the widgets in Kivy GUI framework have the capability to handle multi-touch gestures. In this tutorial, you will learn to build attractive GUI applications with Kivy GUI library. This tutorial is a good starting point for anybody who wants to develop cross-platform GUI apps. Audience This tutorial is a good starting point for anybody who wants to develop cross-platform GUI apps. Kivy is also a good choice for mobile app development for Android an iOS devices. One can follow the examples in this tutorial to develop attractive desktop GUI applications and mobile apps. Prerequisites Since kivy is a Python library, an intermediate level knowledge of Python programming is required. Good understanding of principles of Object-oriented programming will be an added advantage. For Android-based apps, you need to have a basic understanding of how the APKs are built and deployed. Print Page Previous Next Advertisements ”;

Kivy – Hello World

Kivy – Hello World ”; Previous Next Let us start with building a simple “Hello World” application using Kivy. Follow the steps given below − To develop a Kivy application, you need to import the App class from the “kivy.app” module. from kivy.app import App An object of the class that uses App as its base, represents the application. To design the interface, override the build() method, which returns a root widget. For now let us put a pass statement in the build() method. class HelloApp(App): def build(self): pass Next, instantiate the above “HelloApp” class − app = HelloApp() The run() method of App class starts an infinite event loop. It displays a blank application window that currently doesn”t have any widget. app.run() Now let us add a non-editable label with “Hello World” caption to the root widget. For this, we have to import the Label class from the “kivy.uix.label” module. Change the build() method as shown in the following program. Hello World in Python Kivy Here is the complete code to print “Hello World” in Kivy − Example from kivy.app import App from kivy.uix.label import Label class HelloApp(App): def build(self): l1 = Label(text=”Hello World”, font_size=50) return l1 app = HelloApp() app.run() The Label object can be configured with many properties. Here, we are just setting the text and font_size properties. Run the above code (hello.py) from the command line − python hello.py Kivy generates some more log text in the terminal [INFO ] [Factory] 190 symbols loaded [INFO ] [Image ] Providers: img_tex, img_dds, img_sdl2, img_pil (img_ffpyplayer ignored) [INFO ] [Text ] Provider: sdl2 [INFO ] [Window ] Provider: sdl2 [INFO ] [GL ] Using the “OpenGL” graphics system [INFO ] [GL ] GLEW initialization succeeded [INFO ] [GL ] Backend used <glew> [INFO ] [GL ] OpenGL version <b”4.6.0 – Build 31.0.101.3959”> [INFO ] [GL ] OpenGL vendor <b”Intel”> [INFO ] [GL ] OpenGL renderer <b”Intel(R) Iris(R) Xe Graphics”> [INFO ] [GL ] OpenGL parsed version: 4, 6 [INFO ] [GL ] Shading version <b”4.60 – Build 31.0.101.3959”> [INFO ] [GL ] Texture max size <16384> [INFO ] [GL ] Texture max units <32> [INFO ] [Window ] auto add sdl2 input provider [INFO ] [Window ] virtual keyboard not allowed, single mode, not docked [INFO ] [Base ] Start application main loop [INFO ] [GL ] NPOT texture support is available When you run this application, you get the default Kivy application window with a label having “Hello World” text on it. You can press the “X” button to close the window and stop the running application. Layouts in Kivy In the above program, we have used only one widget, i.e., Label, in the root tree of the application. If we want to place more than one widgets, we need to add them in a Layout and then return the Layout object from the build() method. Kivy supports various types of layouts such as BoxLayout, FlowLayout, AnchorLayout and more. Let us design the interface such that two Labels are added in a vertical BoxLayout object. The labels are added one below the other. The build() method of the HelloApp class will be changed accordingly. Example from kivy.app import App from kivy.uix.label import Label from kivy.uix.boxlayout import BoxLayout class HelloApp(App): def build(self): lo = BoxLayout(orientation=”vertical”) l1 = Label(text=”Hello World”, font_size=50) l2 = Label(text = “From TutorialsPoint”, font_size=30, color = (1,0,0,1)) lo.add_widget(l1) lo.add_widget(l2) return lo app = HelloApp() app.run() Output Run the above program to obtain the following output − Print Page Previous Next Advertisements ”;

Kivy – Installation

Kivy – Installation ”; Previous Next To build a Kivy application, you need to have Python installed in your computer. Kivy 2.2.0, the latest stable version, officially supports Python versions 3.7 to 3.11. If Python is not already installed, download the installer of latest Python version, appropriate for your operating system and architecture, from Python”s official website − https://www.python.org/downloads/ Python Virtual Environment Python recommends the use of virtual environment to avoid conflicts with other Python versions and packages. A virtual environment allows us to create an isolated working copy of Python for a specific project without affecting the outside setup. We shall use the “venv” module in Python”s standard library to create virtual environment. PIP is included by default in Python version 3.4 or later. Creating a Virtual Environment Use the following command to create a virtual environment in Windows − C:usersuser>python -m venv c:kivyenv On Ubuntu Linux, update the APT repo and install “venv”, if required, before creating a virtual environment. mvl@GNVBGL3:~ $ sudo apt update && sudo apt upgrade -y mvl@GNVBGL3:~ $ sudo apt install python3-venv Then, use the following command to create a virtual environment − mvl@GNVBGL3:~ $ sudo python3 -m venv kivyenv Activating a Virtual Environment You need to activate the virtual environment. On Windows, use the following command − C:>cd kivyenv C:kivyenv>scriptsactivate (kivyenv) C:kivyenv> On Ubuntu Linux, use the following command to activate the virtual environment − mvl@GNVBGL3:~$ cd kivyenv mvl@GNVBGL3:~/kivyenv$ source bin/activate (myenv) mvl@GNVBGL3:~/kivyenv$ Installing Kivy Using the pip Utility The easiest way to install any Python package is with the use of “pip” utility. Python 3 installation comes with the “pip” installer. After activating the virtual environment, use the following command from the CMD terminal in Windows or Linux terminal − pip3 install “kivy[base]” kivy_examples This installs the Kivy package with minimal dependencies. The “kivy_examples” package is optional. Instead of “base”, the “full” option enables audio/video support. Installing the Dependency Libraries for Kivy SDL2 (Simple DirectMedia Layer) is a major dependency for Kivy. On Windows OS, SDL2 is automatically installed when you use the “pip” utility. However, for Linux and macOS, you need to install SDL2 separately. On macOS, you can install SDL2 using Homebrew by running the following command in your terminal − brew install sdl2 If on Linux OS, use the corresponding package manager to install SDL2. For example, it is done with the following command on Ubuntu Linux machine − sudo apt-get install libsdl2-dev Additionally, you may have to install other dependencies such as “gstreamer” and “Pillow” for certain specific features of Kivy. Verifying the Kivy Installation To verify if Kivy has been properly installed, start the Python interactive shell and import the package. The console shows that the Kivy dependencies are also imported. >>> import kivy [INFO] [Logger] Record log in C:Usersmlath.kivylogskivy_23-05-26_0.txt [INFO] [deps] Successfully imported “kivy_deps.gstreamer” 0.3.3 [INFO] [deps] Successfully imported “kivy_deps.angle” 0.3.3 [INFO] [deps] Successfully imported “kivy_deps.glew” 0.3.1 [INFO] [deps] Successfully imported “kivy_deps.sdl2” 0.6.0 [INFO] [Kivy] v2.2.0 [INFO] [Kivy] Installed at “c:kivyenvLibsite-packageskivy__init__.py” [INFO] [Python] v3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)] [INFO] [Python] Interpreter at “c:kivyenvScriptspython.exe” [INFO] [Logger] Purge log fired. Processing… [INFO] [Logger] Purge finished! You can also obtain the list of all the packages installed using the “pip freeze” command − (kivyenv) C:kivyenv>pip3 freeze certifi==2023.5.7 charset-normalizer==3.1.0 docutils==0.20.1 idna==3.4 Kivy==2.2.0 kivy-deps.angle==0.3.3 kivy-deps.glew==0.3.1 kivy-deps.gstreamer==0.3.3 kivy-deps.sdl2==0.6.0 Kivy-examples==2.2.0 Kivy-Garden==0.1.5 Pillow==9.5.0 Pygments==2.15.1 pypiwin32==223 pywin32==306 requests==2.31.0 urllib3==2.0.2 Print Page Previous Next Advertisements ”;

Kivy – Behaviors

Kivy – Behaviors ”; Previous Next In Kivy, the “kivy.uix.behaviors” module defines behavior mixins, which are also called “reusable classes” that provide additional functionality to widgets. They encapsulate common functionality and can be mixed in with multiple widgets to extend their behavior. Behaviors help in keeping the code modular, reusable, and maintainable. They allow you to define your own implementation for standard kivy widgets that can act as drop-in replacements. One of the applications of behavior mixins can be the use of an image as a button. We can define a custom class that extends ButtonBehavior to make it respond to events like “on_press” or “on_touch” so that the image itself can behave as a button. Later in this chapter, we shall have a look at the example of converting an image into a button. The “kivy.uix.behaviors” module defines several mixins. Some of the most frequently used classes are explained below − ButtonBehavior This behavior provides button-like functionality to widgets. It adds features such as press/release visual feedback, automatic triggering of the “on_press” and “on_release” events, and handling of touch events. It is often used with widgets like Button, ToggleButton, or custom widgets that need button-like behavior. DragBehavior This behavior class allows widgets to be dragged and moved by touch input. It handles touch events such as on_touch_down, on_touch_move, and on_touch_up to implement dragging functionality. It is useful for creating draggable widgets in your application. FocusBehavior This behavior provides support for managing focus among widgets. It allows widgets to receive keyboard input and handle focus-related events. It is useful for implementing keyboard navigation and managing focus traversal within your application. SelectableBehavior This behavior adds selection functionality to widgets. It allows users to select one or more items from a group of selectable widgets. It handles selection state, visual feedback, and triggering of selection-related events. It is often used with widgets like ListView, RecycleView, or custom widgets that require selection functionality. ButtonBehavior Example We shall now develop a Kivy program to implement ButtonBehavior. We use Kivy”s Image object to display an image on Kivy window. However, to add button-like behavior to it, we first define a custom class called imgbtn that extends Image as well as ButtonBehavior classes. The source property of Image class is assigned a string which is the path to the image file. We then override the on_press() method as shown below − from kivy.uix.image import Image from kivy.uix.behaviors import ButtonBehavior class imgbtn(ButtonBehavior, Image): def __init__(self, **kwargs): super(imgbtn, self).__init__(**kwargs) self.source = ”Logo.jpg” def on_press(self): print(“Button pressed”) After this, the imgbtn class is defined. Let the build() method of the App class return its object. Here is the ready-to-run code. You can save and run it − from kivy.app import App from kivy.uix.image import Image from kivy.uix.behaviors import ButtonBehavior from kivy.config import Config # Configuration Config.set(”graphics”, ”width”, ”720”) Config.set(”graphics”, ”height”, ”400”) Config.set(”graphics”, ”resizable”, ”1”) class imgbtn(ButtonBehavior, Image): def __init__(self, **kwargs): super(imgbtn, self).__init__(**kwargs) self.source = ”Logo.jpg” def on_press(self): print(“Button pressed”) class ImageApp(App): def build(self): return imgbtn() if __name__ == ”__main__”: ImageApp().run() Output Run the above program. It will display a Kivy window with the image at its center − Note that the image itself acts as a button. To test, click the image and it will print the following message on the console − Button pressed Print Page Previous Next Advertisements ”;