Kivy – OpenGL

Kivy – OpenGL ”; Previous Next The Kivy framework is equipped with powerful graphics capabilities built on top of OpenGL and SDL instructions. Kivy uses OpenGL ES 2 graphics library, and is based on Vertex Buffer Object and shaders. The “kivy.graphics.opengl” module is a Python wrapper around OpenGL commands. A shader is a user-defined program designed to run on some stage of a graphics processor. Shaders are written in OpenGL Shading Language (GLSL), which is a high-level shading language with a syntax based on the C programming language. The two commonly used shaders to create graphics on the web are Vertex Shaders and Fragment (Pixel) Shaders. Vertex shaders − They take the input from the previous pipeline stage (e.g. vertex positions, colors, and rasterized pixels) and customize the output to the next stage. Fragment shaders − They take 2D position of all pixels as input and customize the output color of each pixel. A detailed discussion on the features and syntax of GLSL is beyond the scope of this tutorial. We shall use an open-source shader file (kaleidoscope.glsl) in this chapter. #ifdef GL_ES precision highp float; #endif uniform vec2 resolution; uniform float time; uniform sampler2D tex0; uniform sampler2D tex1; void main(void){ vec2 p = -1.0 + 2.0 * gl_FragCoord.xy / resolution.xy; vec2 uv; float a = atan(p.y,p.x); float r = sqrt(dot(p,p)); uv.x = 7.0*a/3.1416; uv.y = -time+ sin(7.0*r+time) + .7*cos(time+7.0*a); float w = .5+.5*(sin(time+7.0*r)+ .7*cos(time+7.0*a)); vec3 col = texture2D(tex0,uv*.5).xyz; gl_FragColor = vec4(col*w,1.0); } In our Kivy application code, we use a .kv file that simply draws a rectangle on the canvas of a FloatLayout widget. <ShaderWidget>: canvas: Color: rgb: 1, 0, 0 Rectangle: pos: self.pos size: self.size The ShaderWidget rule of this “kv” file corresponds to the ShaderWidget class. It schedules a clock interval to be fired after each second to update the glsl variables in the shader definition. class ShaderWidget(FloatLayout): fs = StringProperty(None) def __init__(self, **kwargs): self.canvas = RenderContext() super(ShaderWidget, self).__init__(**kwargs) Clock.schedule_interval(self.update_glsl, 1 / 60.) The “fs” class variable stores the code from glsl file. The RenderContext() method from kivy.graphics module stores all the necessary information for drawing, i.e., the vertex shader and the fragment shader, etc. The “fs” StringProperty is bound to the “on_fs()” method which will set the shader. def on_fs(self, instance, value): shader = self.canvas.shader old_value = shader.fs shader.fs = value if not shader.success: shader.fs = old_value raise Exception(”failed”) The update_glsl() method will be called each time the scheduled clock event occurs. It basically updates the fragment color of each pixel on the application window. def update_glsl(self, *largs): self.canvas[”time”] = Clock.get_boottime() self.canvas[”resolution”] = list(map(float, self.size)) win_rc = Window.render_context self.canvas[”projection_mat”] = win_rc[”projection_mat”] self.canvas[”modelview_mat”] = win_rc[”modelview_mat”] self.canvas[”frag_modelview_mat”] = win_rc[”frag_modelview_mat”] The App class simple loads the ShaderWidget from the kv file and class definition. Example The complete code is given below − from kivy.clock import Clock from kivy.app import App from kivy.uix.floatlayout import FloatLayout from kivy.core.window import Window from kivy.graphics import RenderContext from kivy.properties import StringProperty from kivy.core.window import Window Window.size=(720,400) file=open(”kaleidoscope.glsl”) shader=file.read() class ShaderWidget(FloatLayout): fs = StringProperty(None) def __init__(self, **kwargs): self.canvas = RenderContext() super(ShaderWidget, self).__init__(**kwargs) Clock.schedule_interval(self.update_glsl, 1 / 60.) def on_fs(self, instance, value): shader = self.canvas.shader old_value = shader.fs shader.fs = value if not shader.success: shader.fs = old_value raise Exception(”failed”) def update_glsl(self, *largs): self.canvas[”time”] = Clock.get_boottime() self.canvas[”resolution”] = list(map(float, self.size)). win_rc = Window.render_context self.canvas[”projection_mat”] = win_rc[”projection_mat”] self.canvas[”modelview_mat”] = win_rc[”modelview_mat”] self.canvas[”frag_modelview_mat”] = win_rc[”frag_modelview_mat”] class ”kaleidoscopeApp(App): title=”kaleidoscope” def build(self): return ShaderWidget(fs=shader) ”kaleidoscopeApp().run() Output Run this code and check the output − Print Page Previous Next Advertisements ”;

Kivy – Tree View

Kivy – Tree View ”; Previous Next Most of the GUI toolkits, including Kivy, provide a TreeView widget with which a user can navigate and interact with hierarchical data presented as nodes in a tree-like format. The file and directory structure shown in the file explorer of an operating system is a typical example of TreeView. The “kivy.uix.treeview” module includes the definitions of three important classes: TreeView, TreeViewNode, and TreeViewLabel. Objects of these classes constitute the tree view widget. A TreeView is populated by the instances of TreeViewNode instances. Any widget from the library such as a label or a button, or a user-defined widget object is combined with TreeViewNode. The root of the tree view is the TreeView object itself. from kivy.uix.treeview import TreeView tv = TreeView() One or more nodes can be directly added below this root. A TreeViewLabel is used as argument for add_node method from kivy.uix.treeview import TreeViewLabel n1 = tv.add_node(TreeViewLabel(text=”node 1”)) Instead of adding a node to the root of the tree, you can add it to a node itself. Provide the instance of the parent node as the second argument to the add_node() method − n2 = tv.add_node(TreeViewLabel(text=”Political Sci”), n1) The root widget of the tree view is opened by default and its default caption is ”Root”. To change that, you can use the TreeView.root_options property. This will pass options to the root widget − tv = TreeView(root_options=dict(text=”My root”)) The TreeViewLabel itself is a label, and hence cannot generate any event as on_press. For that you should define a class that inherits TreeView and a Button. class TreeViewButton(Button, TreeViewNode): pass You can then process different events such as − on_node_expand − Fired when a node is being expanded on_node_collapse − Fired when a node is being collapsed Example The code given below composes a simple tree view of subjects available in each faculty of a college. A vertical box layout houses a treeview widget and a button. The root of the tree view is open. To expand a node, click the “>” button to its left. It turns to a downward arrow. If clicked again, the node is collapsed. from kivy.app import App from kivy.uix.treeview import TreeView, TreeViewLabel from kivy.uix.button import Button from kivy.uix.boxlayout import BoxLayout from kivy.core.window import Window Window.size = (720, 350) class DemoApp(App): def build(self): lo = BoxLayout(orientation=”vertical”) self.tv = TreeView(root_options={ ”text”: ”Faculty-wise Subjects”, ”font_size”: 20} ) self.n1 = self.tv.add_node(TreeViewLabel(text=”Arts”)) self.n2 = self.tv.add_node(TreeViewLabel(text=”Commerce”)) self.n3 = self.tv.add_node(TreeViewLabel(text=”Science”)) self.n4 = self.tv.add_node( TreeViewLabel(text=”Sociology”), self.n1 ) self.n5 = self.tv.add_node( TreeViewLabel(text=”History”), self.n1 ) self.n6 = self.tv.add_node( TreeViewLabel(text=”Political Sci”), self.n1 ) self.n7 = self.tv.add_node( TreeViewLabel(text=”Accountancy”), self.n2 ) self.n8 = self.tv.add_node( TreeViewLabel(text=”Secretarial Practice”), self.n2 ) self.n9 = self.tv.add_node( TreeViewLabel(text=”Economics”), self.n2 ) self.n10 = self.tv.add_node( TreeViewLabel(text=”Physics”), self.n3 ) self.n11 = self.tv.add_node( TreeViewLabel(text=”Mathematics”), self.n3 ) self.n12 = self.tv.add_node( TreeViewLabel(text=”Chemistry”), self.n3 ) lo.add_widget(self.tv) return lo DemoApp().run() Output 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 ”;

Kivy – Applications

Kivy – Applications ”; Previous Next An application written with the Kivy framework is represented by an object of a class that inherits the “kivy.app.App” class. Calling the run() method of this object starts the application, and enters in an infinite event loop. Application GUI is set up either by overriding the build() method in App class, or by providing a corresponding “.kv” file. Application Configuration If you want to provide a customized configuration of one or more parameters, a config.ini file will be created when build_config() method of the App class is invoked. Here is an example of build_config() method. It stores values for two parameters in “section1” of the “ini” file. The name of “ini” file will be the same as the app class (without “App” suffix if it has). So, if your app class is “HelloApp”, then the “ini” file will be created as “hello.ini”. The parameters from this file will be loaded when the build() method is invoked. def build_config(self, config): config.setdefaults(”section1”, { ”Company”: ”TutorialsPoint”, ”year”: ”2023” }) As soon as a section is added, the “hello.ini” file will be created in the same directory which contains the “hello.py” file. Load and use the configuration settings in the build() method as follows − def build(self): config = self.config l1 = Label(text=”© {} Year {}”.format( config.get(”section1”, ”company”), config.getint(”section1”, ”year”)), font_size=40) return l1 When the application is run, the Label will be populated by reading the “config” file. Example Here is the complete program − from kivy.app import App from kivy.uix.label import Label from kivy.core.window import Window class HelloApp(App): Window.size = (720, 300) def build_config(self, config): config.setdefaults(”section1”, { ”Company”: ”TutorialsPoint”, ”year”: ”2023” }) def build(self): config = self.config l1 = Label(text=”© {} Year {}”.format( config.get(”section1”, ”company”), config.getint(”section1”, ”year”)), font_size=40) return l1 app = HelloApp() app.run() Output When you run the application, it will produce the following window as the output − Look for the “hello.ini” file created in the application folder. When opened with a text editor, it shows the following contents − [section1] company = TutorialsPoint year = 2023 Instance Methods in the App Class The App class defines the following instance methods − build() − This method initializes the application and is called only once. If this method returns a widget (tree), it will be used as the root widget and added to the window. build_config() − This method constructs ConfigParser object before the application is initialized. Based on any default section / key / value for your config that you put here, the “ini” file will be created in the local directory. load_config() − This function returns a ConfigParser with the application configuration. load_kv() − This method is invoked the first time the app is being run if no widget tree has been constructed before for this app. This method then looks for a matching the “kv” file in the same directory as file that contains the application class. pause() − This method causes the application to be paused. run() − When called, this method launches the app in standalone mode. stop() −This method stops the application. on_pause() − This is an event handler method that is called when Pause mode is requested. If it returns True, the app can go into Pause mode, otherwise the application will be stopped. on_resume() − An event handler method which resumes the application from the Pause mode. on_start() − This method is the event handler for the ”on_start” event. It is fired after initialization (after build() has been called) but before the application has started running. on_stop() − The ”on_stop” event which is fired when the application has finished running (i.e., the window is about to be closed). This method handles on_stop event. 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 ”;