Kivy – Input Recorder

Kivy – Input Recorder ”; Previous Next The functionality of Recorder class in Kivy framework is still under development, and is still at experimental stage. The Recorder object records the input events such as touch events, key events and click events. They are recorded in a file with a “.kvi” extension. Kivy uses this file and replays the events by generating equivalent fake events and dispatches them to the event loop. The Recorder class is defined in the “kivy.input.recorder” module − from kivy.input.recorder import Recorder rec = Recorder(**kwargs) To start recording, press F8 after the Recorder object is instantiated. The event data is recorded in the “recorder.kvi” file in the current folder. You can specify any other filename to the file attribute. rec = Recorder(filename=”myrecorder.kvi”) Press F7 to replay the events. To control the recording and replay manually, use the record and play properties of the Recorder object. To start recording − rec = Recorder(filename=”myrecorder.kvi”) rec.record = True rec.start() To stop recording − rec.record = False rec.stop() Similarly, to start replay − rec.play = True rec.start() and, to stop playback − rec.play = False rec.stop() You can make the replay go on in a loop − def playloop(instance, value): if value is False: instance.play = True rec = Recorder(filename=”myrecorder.kvi”) rec.bind(play=playloop) rec.play = True Example In the code given below, a Label is added to a Scatter widget, so that you can perform rotation, zooming and transformation. Further, the text property of the label updates as the user changes the contents of the TextInput box. The recording and replay of events is defined on the on_press event of two buttons. Here”s the complete code − from kivy.app import App from kivy.uix.label import Label from kivy.uix.scatter import Scatter from kivy.uix.boxlayout import BoxLayout from kivy.uix.textinput import TextInput from kivy.uix.togglebutton import ToggleButton from kivy.input.recorder import Recorder from kivy.core.window import Window Window.size = (720,400) class scatterdemoapp(App): def build(self): self.rec = Recorder(filename=”myrecorder.kvi”) box=BoxLayout(orientation=”vertical”) box1=BoxLayout(orientation=”horizontal”) text1=TextInput(text=”Hi”, pos_hint={”top”:1},height=100, size_hint=(.5, None)) b1=ToggleButton(text=”record”,pos_hint={”top”:1}, height=100, size_hint=(.25, None)) b1.bind(on_press=self.on_recording) b2=ToggleButton(text=”play”, pos_hint={”top”:1},height=100, size_hint=(.25, None)) b2.bind(on_press=self.on_playing) box1.add_widget(text1) box1.add_widget(b1) box1.add_widget(b2) box.add_widget(box1) scatr=Scatter() self.lbl=Label(text=”Hi”, font_size=60, pos=(Window.width/2-100,200 )) text1.bind(text=self.lbl.setter(”text”)) scatr.add_widget(self.lbl) box.add_widget(scatr) return box def on_recording(self, obj): if obj.state==”down”: self.rec.record=True self.rec.start() else: self.rec.record=False self.rec.stop() def on_playing(self, obj): if obj.state==”down”: self.rec.play=True self.rec.start() else: self.rec.play=False self.rec.stop() scatterdemoapp().run() Output The App window appears as shown here − Hit the record button and all the screen activities including the key_down events are recorded in the “.kvi” file. The console window shows that inputs have been recorded. [INFO ] [Recorder ] Recording inputs to ”myrecorder.kvi” [INFO ] [Recorder ] Recorded 901 events in ”myrecorder.kvi” On pressing the play button to replay the recorded events. Accordingly the console echoes the corresponding log. [INFO ] [Recorder ] Start playing 901 events from ”myrecorder.kvi” Print Page Previous Next Advertisements ”;

Kivy – Canvas Stress

Kivy – Canvas Stress ”; Previous Next In this chapter, we shall find out how efficient is the graphics engine. This can be done by adding a large number of graphics instructions to the canvas of a Kivy object. The program given below measures the time required by the graphics engine to draw ten thousand rectangles at random positions and with randomly chosen color value. Thus it will give an evaluation of how much stress the canvas can sustain. Syntax A rectangle instruction is drawn on the canvas of any Kivy widget with the following syntax − with self.root.canvas: Color(r,g,b,a) Rectangle(pos, size) We shall generate random values for RGB as well as x and y coordinates for the rectangle and display 10, 000 rectangles. The time taken for it is calculated by the perf_counter() function. t1=perf_counter() with self.root.canvas: for i in range(10000): Color(r,g,b,a) Rectangle(pos, size) t2=perf_counter() The time required to draw will be “t2 – t1”. It will be displayed on the title bar of the Kivy app window. Example The complete program is as follows − from kivy.app import App from kivy.graphics import * from kivy.uix.floatlayout import FloatLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.button import Button from random import random as r from time import perf_counter from kivy.core.window import Window Window.size = (720, 400) class StresstestApp(App): def add_rects(self, *args): self.t1 = perf_counter() with self.root.canvas: for i in range(10000): Color(r(), 1, 1, mode=”hsv”) Rectangle( pos=(r() * self.root.width + self.root.x, r() * self.root.height + self.root.y), size=(20, 20) ) self.t2 = perf_counter() self.title = str(self.t2 – self.t1) + “Sec. to draw 10000 rectangles” def build(self): main = GridLayout(cols=1) self.root = FloatLayout(size=(Window.width, 100)) self.btn1 = Button( text=”start”, size_hint=(1, None), pos_hint={”center_x”: .5, ”center_y”: .1} ) self.btn1.bind(on_press=self.add_rects) self.root.add_widget(self.btn1) main.add_widget(self.root) return main StresstestApp().run() Output Run the program and click the “start” button. You will get the time taken displayed on the title bar as shown in the following figure − Print Page Previous Next Advertisements ”;

Kivy – Widget Animation

Kivy – Widget Animation ”; Previous Next Any widget in Kivy toolkit can be animated. All you need to do is define an object of Animation class, choose at least one property of the target widget to animate and specify its final value to be reached after the animation effect is complete. Call the start() method of the Animation object, passing the target widget to it. anim = Animation(property1=value1, property2=value2, ..) anim.start(widget) In the following example, we have placed four Kivy Buttons. Two buttons are placed along the X-axis, keeping the “y” coordinate to 0 and randomizing the “x” coordinate so that one button is placed in first half and the other in second half. Similarly, two more buttons are placed along the Y-axis, their “x” coordinate as 0 and y coordinate value assigned randomly. Buttons placed along X-axis are animated to move up and down. The “y” coordinate value starts from its initial value all the way upto the maximum height of the window, and back to original position. The up and down movement is looping as the repeat property is set to True. Both horizontally placed buttons are bound to the method below − def animate1(self, instance): animation = Animation(pos=(instance.pos[0], Window.height)) animation += Animation(pos=(instance.pos[0], 0)) animation.repeat=True animation.start(instance) Similarly, the vertically arranged buttons b3 and b4 are bound to the following method. Their “x” coordinate value changes from their current value to maximum width and back. def animate2(self, instance): animation = Animation(pos=(Window.width, instance.pos[1])) animation += Animation(pos=(0, instance.pos[1])) animation.repeat=True animation.start(instance) While animation of each button can begin by pressing each button, we can make all the four buttons start animating simultaneously on a touch down event. The above callbacks are triggered by the trigger_action() method. def on_touch_down(self, *args): self.b1.trigger_action(5) self.b2.trigger_action(10) self.b3.trigger_action(15) self.b4.trigger_action(20) Rest of the code is just setting up the UI of four buttons in the build() method of the App class. Example Here”s the complete code − import kivy kivy.require(”1.0.7”) import random from kivy.animation import Animation from kivy.app import App from kivy.uix.button import Button from kivy.uix.floatlayout import FloatLayout from kivy.core.window import Window Window.size = (720,400) class TestApp(App): def animate1(self, instance): animation = Animation(pos=(instance.pos[0], Window.height)) animation += Animation(pos=(instance.pos[0], 0)) animation.repeat=True animation.start(instance) def animate2(self, instance): animation = Animation(pos=(Window.width, instance.pos[1])) animation += Animation(pos=(0, instance.pos[1])) animation.repeat=True animation.start(instance) def on_touch_down(self, *args): self.b1.trigger_action(5) self.b2.trigger_action(10) self.b3.trigger_action(15) self.b4.trigger_action(20) def build(self): box=FloatLayout() # create a button and attach animate() method # as a on_press handler self.b1 = Button( size_hint=(.15, .08), text=”BTN1”, pos=(random.randint(Window.width/2, Window.width), 0), on_press=self.animate1 ) self.b2 = Button( size_hint=(.15, .08), text=”BTN2”, pos=(random.randint(0, Window.width/2), 0), on_press=self.animate1 ) self.b3 = Button( size_hint=(.15, .08), text=”BTN3”, pos=(0, random.randint(0, Window.height/2)), on_press=self.animate2 ) self.b4 = Button( size_hint=(.15, .08), text=”BTN4”, pos=(0, random.randint(Window.height/2, Window.height)), on_press=self.animate2 ) box.add_widget(self.b1) box.add_widget(self.b2) box.add_widget(self.b3) box.add_widget(self.b4) box.bind(on_touch_down=self.on_touch_down) return box if __name__ == ”__main__”: TestApp().run() Output The program starts with the button position randomized. Click anywhere on the application window. Buttons b1 and b2 will start moving up and down. Buttons b3 and b4 will start moving back and forth. This is the initial position − The following figure is a screenshot of button positions while they are moving − Print Page Previous Next Advertisements ”;

Kivy – Recycle Layout

Kivy – Recycle Layout ”; Previous Next Very often, if an application interface requires a large number of widgets to display data items, its performance declines. The RecycleView widget in Kivy provides a flexible alternative. With the RecycleView, it is possible to view only a selected section of a large data set. It has the ability to reuse the widgets to show a list of scrollable data items. This feature is very useful for letting the user scroll through list of products, images, etc. The mechanism of recycle layout is based on MVC (Model-View-Controller) architecture. The RecycleView.data property forms the model layer. The RecycleDataModel class implements the View layer. The View is split across layout and views and implemented using adapters. It is defined in the RecycleLayout, which is an abstract class. For the third component – Controller – the RecycleViewBehavior class and defines the logical interaction. The RecycleView class implements the logic. It is defined in the “kivy.uix.recycleview” module. You need to instantiate a RecycleView object, it automatically creates the views and data classes. Two important properties of the RecycleView that must be set are viewclass and data. viewclass − Set this property to the name of a widget class. The recyclable view will consist of objects of this class. For example, if viewclass is a Button, the recycle view will be a scrollable list of buttons. Any widget can be used as the value of this property. data − data is essentially a list of dicts, and uses these dicts to generate instances of the viewclass as required. This is a list of dicts whose keys map to the corresponding property names of the viewclass. For example, if the viewclass is set to Button, the data can be a list of dict items, in each dictionary, the key should be one of the properties of the Button class. The RecycleView widget tree must also include a certain layout manager so that the view port can be found. There are two layouts to be used with RecycleView. One is RecycleBoxLayout (available in “kivy.uix.recycleboxlayout” module) and the other is RecycleGridLayout (in “kivy.uix.recyclegridlayout” module). Both the layout classes inherit BoxLayout and GridLayout classes. Example Let us load a hundred buttons in the RecycleView widget. The are added to RecycleBoxLayout. To use buttons as elements in the recycle view, set its viewclass to Button. Its data property is a list of dicts. Each dict has ”text” key and the value of each key is the button caption as BTN 1, BTN 2, etc. The following list comprehension statement composes the dict as − data=[{”text”: ”BTN {}”.format(str(x))} for x in range(20)] [{”text”: ”BTN 0”}, {”text”: ”BTN 1”}, {”text”: ”BTN 2”}, {”text”: ”BTN 3”}, {”text”: ”BTN 4”}, {”text”: ”BTN 5”}, {”text”: ”BTN 6”}, {”text”: ”BTN 7”}, {”text”: ”BTN 8”}, {”text”: ”BTN 9”}, {”text”: ”BTN 10”}, {”text”: ”BTN 11”}, {”text”: ”BTN 12”}, {”text”: ”BTN 13”}, {”text”: ”BTN 14”}, {”text”: ”BTN 15”}, {”text”: ”BTN 16”}, {”text”: ”BTN 17”}, {”text”: ”BTN 18”}, {”text”: ”BTN 19”}] Here is the “kv” language script for the RecycleView app − RecycleView: viewclass: ”Button” data: [{”text”: ”BTN {}”.format(str(x))} for x in range(20)] RecycleBoxLayout: default_size: None, dp(56) default_size_hint: 1, None size_hint_y: None height: self.minimum_height orientation: ”vertical” The App class simply has to load this “kv” file, just keep the build() method with a pass statement. from kivy.app import App from kivy.uix.button import Button from kivy.core.window import Window Window.size = (720,400) class recycled(App): def build(self): pass recycled().run() Output Test the output of the code by running the above Python script. You should get a scrollable view of the buttons as shown below − Print Page Previous Next Advertisements ”;

Kivy – reStructuredText

Kivy – reStructuredText ”; Previous Next reStructuredText is a file format for a text file containing data used primarily in the Python for technical documentation. The file usually has a “.rst” extension. reStructuredText is a part of the DocUtils project, and its main purpose is to provide a set of tools for Python that are similar to Javadoc for Java. Written by David Goodger, its earliest version was released in 2001, the latest being in 2019. reStructuredText can be considered as a lightweight markup language, with lot of similarities with MarkDown syntax. It is being used as a core component of Python”s Sphinx document generation system. Kivy provides reStructuredText document renderer in the form of RstDocument class defined in the “kivy.uix.rst” module. from kivy.uix.rst import RstDocument doc = RstDocument(**kwargs) Formatting reStructuredText Paragraph − A chunk of text that is separated by blank lines (one is enough). Paragraphs must have the same indentation. Bold − Characters between two asterisks (example:**Hello**) Italics − characters between single asterisks(ex: *world*) Enumerated list − Start a line off with a number or letter followed by a period “.”, right bracket “)” or surrounded by brackets “( )”. For example − 1. Python 2. Java 3. C++ Bulleted list − start the line off with a bullet point character – either “-“, “+” or “*” Sections − These are a single line of text (one or more words) with adornment: an underline alone, or an underline and an overline together, in dashes “—–“, equals “======” Images − To include an image in your document, you use the the image directive. For example − .. image:: kivi-logo.png Example Following text is formatted as per the reStructuredText syntax. Save the following text as index.rst − ================ Welcome to Kivy ================ Welcome to Kivy”s documentation. **Kivy** is an open source software library for the rapid development of applications equipped with novel user interfaces, such as multi-touch apps. With Kivy, you can create apps that run on: * Desktop computers: macOS, Linux, *BSD Unix, Windows. * iOS devices: iPad, iPhone. * Android devices: tablets, phones. ——————- Virtual environment ——————- Create the virtual environment named kivy_venv in your current directory_:: python -m virtualenv kivy_venv Activate the *virtual environment*. For Windows default CMD, in the command line do_:: kivy_venvScriptsactivate Your terminal should now preface the path with something like (kivy_venv), indicating that the kivy_venv environment is active. If it doesn”t say that, the virtual environment is not active and the following won”t work. Install Kivy ———— The simplest is to install the current stable version of kivy is to use pip_:: python -m pip install “kivy[base]” kivy_examples Let us write a program to render this reStructuredText document in Kivy application. We put a RstDocument widget in a grid layout with a single column. Set the source property of this object to the RST file that we have created. from kivy.app import App from kivy.uix.rst import RstDocument from kivy.uix.gridlayout import GridLayout from kivy.core.window import Window Window.size = (720,400) class rstdemoapp(App): def build(self): grid=GridLayout(cols=1) doc = RstDocument(source=”index.rst”) grid.add_widget(doc) return grid rstdemoapp().run() Output Run the above code. The RST document will be displayed as per the formatting syntax explained above. Print Page Previous Next Advertisements ”;

Kivy – Drawing

Kivy – Drawing ”; Previous Next All the GUI widgets in Kivy library have a Canvas property. Canvas is a place used for drawing various objects such as rectangle, ellipse, etc. It must be noted that Kivy doesn”t have a separate Canvas widget for drawing shapes. Canvases of all widgets share a common coordinate space. In Kivy, drawing is done on a Canvas related to any widget, with vertex instructions and context instructions. Vertex instructions − Instructions used to draw basic geometric shapes like lines, rectangles, ellipses, etc. are called vertex instructions. Context instructions − These instructions don”t draw anything but manipulate the whole coordinate space, so to add colors to it, rotate, translate and scale it. Vertex Instructions These instructions are added to the Canvas in the form of different vertex objects. The vertex classes are defined in kivy.graphics.vertex_instructions module. As mentioned above, the drawing instructions are added to the context of a Canvas. with self.canvas: vertex(**args) The vertex_instructions module includes the following classes − Bezier BorderImage Ellipse Line Mesh Point Quad Rectangle RoundedRectangle SmoothLine Triangle Bezier A Bezier curve is weighted by some control points, that we include within the instruction. In Kivy, Bezier is a vertex canvas instruction that draws this curve from a set of points given to the Beizer constructor as a parameter. from kivy.graphics import Beizer with self.canvas: Beizer(**args) Parameters Following parameters are defined in the Beizer class − points − List of points in the format (x1, y1, x2, y2…) loop − bool, defaults to False, Set the bezier curve to join the last point to the first. segments − int, defaults to 180. Define how many segments are needed for drawing the curve. More number of segments results in smoother drawing. dash_length − Length of a segment (if dashed), defaults to 1. dash_offset − Distance between the end of a segment and the start of the next one, defaults to 0. Changing this makes it dashed. Example self.w=Widget() with self.w.canvas: Color(0,1,1,1) Bezier( points=[700,400,450,300,300,350,350, 200,200,100,150,10], segments=20 ) Color(1,1,0,1) Point( points =[700,400,450,300,300,350,350, 200,200,100,150,10], pointsize= 3 ) Output It will produce the following output window − The points are shown here for reference. Ellipse In Kivy framework, Ellipse is a vertex instruction. Depending on the segments required, it can display a polygon, a rectangle or an arc. If the width and height parameters are equal, the result is a circle. from kivy.graphics import Ellipse with self.canvas: Ellipse(**args) Parameters Following parameters are defined in the Ellipse class − pos − the two element tuple giving the X and Y coordinate values of the center of the ellipse. size − the two element tuple defining the width and height of ellipse in pixels. angle_start − float, defaults to 0.0 specifies the starting angle, in degrees. angle_end − float, defaults to 360.0 specifies the ending angle, in degrees. segments − The number of segments of the ellipse. The ellipse drawing will be smoother if you have many segments. Use this property to create polygons with 3 or more sides. Values smaller than 3 will not be represented. Example self.w=Widget() with self.w.canvas: Color(0.5, .2, 0.4, 1) d = 250 Ellipse(pos=(360,200), size=(d+75, d)) Output It will produce the following output window − Rectangle This vertex instruction draws a rectangle on the canvas, based on the position and dimensions given as parameters. from kivy.graphics import Rectangle with self.canvas: Rectangle(**args) Parameters Following parameters are defined in the Rectangle class − pos − list of integers, specifying Position of the rectangle, in the format (x, y). size − list of integers, Size of the rectangle, in the format (width, height). Drawing a rectangle filled with a certain color is the recommended way of providing background to a label. Example def build(self): widget = Widget() with widget.canvas: Color(0, 0, 1, 1) Rectangle( pos=(50, 300), size_hint=(None, None), size=(300, 200) ) lbl = Label( text=”Hello World”, font_size=24, pos=(Window.width / 2, 300), size=(200, 200), color=(0, 0, 1, 1) ) with lbl.canvas.before: Color(1, 1, 0) Rectangle(pos=lbl.pos, size=lbl.size) widget.add_widget(lbl) return widget Output It will produce the following output window − It may be noted that a Quad is a quadrilateral, a polygon with four vertices and need not be a rectangle. Similarly, a round rectangle is a rectangle with rounded vertices. Line In Kivy graphics, Line is a basic vertex instruction. The points property of Line object constructor has x and y coordinates of successive points. Kivy draws a line connecting the points successively. from kivy.graphics import Line with self.canvas: Line(**args) Parameters Following parameters are defined in the Line class − points − list of points in the format (x1, y1, x2, y2…) dash_length − int Length of a segment (if dashed), defaults to 1. dash_offset − Offset between the end of a segment and the beginning of the next one, defaults to 0. Changing this makes it dashed. dashes − list of ints in the format [ON length, offset, ON length, offset, …]. E.g. [2,4,1,6,8,2] would create a line with the first dash length 2 then an offset of 4 then a dash length of 1 then an offset of 6 and so on. width − float – defines the Width of the line, defaults to 1.0. Example def build(self): box = BoxLayout(orientation=”vertical”) self.w = Widget() with self.w.canvas: Color(1, 0, 0, 1) Line( points=[700, 400, 450, 300, 300, 350, 350, 200, 200, 100, 150, 10], width=4 ) box.add_widget(self.w) return box Output

Kivy – Atlas

Kivy – Atlas ”; Previous Next If your app is expected to work with many images, especially on a remote server, their loading time needs to be optimized. Atlas in Kivy framework helps in reducing the loading time. With Kivy Atlas, the app needs to load just one image file, which is less error prone, and also uses lesser resources than loading several images. The Atlas is often used in Kivy games apps for rendering images. The Atlas class is available in the “kivy.atlas” module. This module can be used to construct an Atlas object programmatically, as well as with its command-line interface. To be able to use Atlas, the current Kivy environment must have the pillow package – an image library for Python. If not available, install it using − pip3 install pillow An Atlas is made up of two files − A json file (it has “.atlas” extension) that contains the image file names and texture locations of the atlas. The image files containing textures referenced by the “.atlas” file. Assuming that the following images are in a directory called imges − Directory of C:kivyenvimages forward.png pause.png play.png previous.png Each of these images is of 64×64 pixels dimension. Hence, we designate an atlas file 0f 256×256 pixels size to accommodate all the four files. Open the command terminal of your OS and run the command − python -m kivy.atlas myatlas 256×256 *.png The terminal shows following log information, at the end of which the two files will be created in the images folder. (kivyenv) C:kivyenvimages>python -m kivy.atlas myatlas 256×256 *.png [INFO ] [Logger ] Record log in C:Usersmlath.kivylogskivy_23-07-20_33.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:kivyenvLibsitepackageskivy__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! [DEBUG ] STREAM b”IHDR” 16 13 [DEBUG ] STREAM b”sRGB” 41 1 [DEBUG ] STREAM b”gAMA” 54 4 [DEBUG ] STREAM b”pHYs” 70 9 [DEBUG ] STREAM b”IDAT” 91 1115 [DEBUG ] STREAM b”IHDR” 16 13 [DEBUG ] STREAM b”sRGB” 41 1 [DEBUG ] STREAM b”gAMA” 54 4 [DEBUG ] STREAM b”pHYs” 70 9 [DEBUG ] STREAM b”IDAT” 91 990 [DEBUG ] STREAM b”IHDR” 16 13 [DEBUG ] STREAM b”sRGB” 41 1 [DEBUG ] STREAM b”gAMA” 54 4 [DEBUG ] STREAM b”pHYs” 70 9 [DEBUG ] STREAM b”IDAT” 91 1230 [INFO ] [Atlas ] create an 256×256 rgba image Atlas created at myatlas.atlas 1 image has been created You can see that two additional files created are myatlas-0.png, which is a 256×256 file comprising of all the images, and an atlas file. forward.png myatlas-0.png myatlas.atlas pause.png play.png previous.png The “.atlas” file is a JSON file containing the information of texture locations of constituent files. {“myatlas-0.png”: {“forward”: [2, 190, 64, 64], “pause”: [68, 190, 64, 64], “play”: [134, 190, 64, 64], “previous”: [2, 124, 64, 64]}} In order to use the Atlas in the Kivy language, we have to use the following format − atlas://path/to/atlas/atlas_name/id. The “id” file refers to the image filename without the extension. For example, if you want to use an image file as a button background in normal state, you would do it as follows − B1 = Button(background_normal=”images/play.png”) Now, aAfter generating the Atlas, you can use the URL ”atlas://images/myatlas/play” as the value. B1=Button(background_normal=”atlas://images/myatlas/play”) Note that in the atlas url, there is no need to add the .atlas extension. It will be automatically appended to the filename. Example Let us the image URLs from the Atlas to set the normal backgrounds for the four buttons – play, pause, forward and previous – on the app window. The atlas files must be created as shown above before running the following code − from kivy.app import App from kivy.graphics import * from kivy.uix.floatlayout import FloatLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.button import Button from kivy.uix.label import Label from kivy.core.window import Window Window.size = (720, 400) class AtlasApp(App): def build(self): main = GridLayout(cols=1) self.l1 = Label(text=”Using Atlas”, font_size=32) main.add_widget(self.l1) root = FloatLayout(size=(Window.width, 100)) with root.canvas: Color(.2, .7, .1, 1) Rectangle(pos=root.pos, size=root.size) self.btn1 = Button( size_hint=(None, None), pos_hint={”center_x”: .2, ”center_y”: .2} ) self.btn2 = Button( size_hint=(None, None), pos_hint={”center_x”: .4, ”center_y”: .2} ) self.btn3 = Button( size_hint=(None, None), pos_hint={”center_x”: .6, ”center_y”: .2} ) self.btn4 = Button( size_hint=(None, None), pos_hint={”center_x”: .8, ”center_y”: .2} ) self.btn1.background_normal = ”atlas://images/myatlas/forward” self.btn2.background_normal = ”atlas://images/myatlas/play” self.btn3.background_normal = ”atlas://images/myatlas/pause” self.btn4.background_normal = ”atlas://images/myatlas/previous” root.add_widget(self.btn1) root.add_widget(self.btn2) root.add_widget(self.btn3) root.add_widget(self.btn4) main.add_widget(root) return main AtlasApp().run() Output When you run this code, it will produce the following output window − Print Page Previous Next Advertisements ”;

Kivy – Useful Resources

Kivy – Useful Resources ”; Previous Next The following resources contain additional information on Kivy. Please use them to get more in-depth knowledge on this topic. Python Flask and SQLAlchemy ORM 22 Lectures 1.5 hours Jack Chan More Detail Python and Elixir Programming Bundle Course 81 Lectures 9.5 hours Pranjal Srivastava More Detail TKinter Course – Build Python GUI Apps 49 Lectures 4 hours John Elder More Detail Print Page Previous Next Advertisements ”;

Kivy – Storage

Kivy – Storage ”; Previous Next The Storage class in Kivy framework is provided to load and store any number of key-value pairs via an indexed entry. The “kivy.storage” module defines the AbstractStore class. Its implementations − DictStore, JsonStore and RedisStore − provide the concrete classes. kivy.storage.dictstore.DictStore: use a python dict as a store. kivy.storage.jsonstore.JsonStore: use a JSON file as a store. kivy.storage.redisstore.RedisStore: use a Redis database with redis-py. To use any of the above storage classes, import the relevant class, declare an object and call its put() method to store the k-v pairs. For JsonStore − from kivy.storage.jsonstore import JsonStore store = JsonStore(”hello.json”) # put some values store.put(name, key1=val1, key2=val2) This will create hello.json file in the current directory. You can retrieve the information with get() method. print (store.get(name)[key]) Following methods are defined in AbstractStore class, which need to be overridden by the concrete implementations like DictStore − clear() − Wipe the whole storage. count() − Return the number of entries in the storage. delete(key) − Delete a key from the storage. If the key is not found, a KeyError exception will be thrown. exists(key) − Check if a key exists in the store. find(**filters) − Return all the entries matching the filters. The entries are returned through a generator as a list of (key, entry) pairs where entry is a dict of key-value pairs. get(key) − Get the key-value pairs stored at key. If the key is not found, a KeyError exception will be thrown. keys() − Return a list of all the keys in the storage. put(key, **values) − Put new key-value pairs (given in values) into the storage. Any existing key-value pairs will be removed. The methods (get(), put() , exists(), delete(), find()) have an asynchronous version. These methods can be called with or without a callback parameter. If given, the callback returns the result to the user when available, as the request will be asynchronous. If the callback is None, then the request will be synchronous and the result will be returned directly. Example Here is the example − # synchronous res=store.get(key) print (res) # asynchronous def my_callback(store, key, result): print (result) store.get(key) The callback function should have these following parameters − store − the ”Store” instance currently used. key − the key sought for. result − the result of the lookup for the key. Example from kivy.storage.jsonstore import JsonStore from kivy.storage.dictstore import DictStore store = JsonStore(”store.json”) # put some values store.put(”state”, name=”Maharashtra”, capital=”Mumbai”, population=”Eleven Cr”) store.put(”os”, name=”Windows”, version=11, released=2021) store.put(”shape”, type=”circle”, radius=5) # using the same index key erases all previously added k-v pairs # get a value using a index key and key print(”Population of ”, store.get(”state”)[”name”], ”is ”, store.get(”state”)[”population”]) print (store.get(”state”).keys()) for k,v in store.get(”state”).items(): print (k,”:”,v) # or guess the key/entry for a part of the key for item in store.find(type=”circle”): print(”Store:”,item[0]) print(”K-V pairs: ”,str(item[1])) Output It will produce the following output − Population of Maharashtra is Eleven Cr dict_keys([”name”, ”capital”, ”population”]) name : Maharashtra capital : Mumbai population : Eleven Cr Store: shape K-V pairs: {”type”: ”circle”, ”radius”: 5} Print Page Previous Next Advertisements ”;

Kivy – Tabbed Panel

Kivy – Tabbed Panel ”; Previous Next Many of the GUI toolkits include a tabbed panel, as it is very convenient to display the interface controls in groups instead of a big form, going well beyond the dimensions of the display device. TabbedPanel widget in Kivy makes it possible to display a widget or a layout in different panels, without making the GUI design look clumsy. The controls in different panels can share the data among themselves. Different tabs are shown as a menu on top with a header area for the actual tab buttons and a content area for showing the current tab content. The TabbedPanel object is the top level container for one or more panels. Corresponding to each panel, a TabbedPanelItem object is added. Each TabbedPAnelItem in turn, can hold any one widget or a layout that contains multiple widgets (such as GridLayout or BoxLayout etc) Both these classes are defined in kivy.uix.tabbedpanel module. from kivy.uix.tabbedpanel import TabbedPanel, TabbedPanelItem A schematic statement flow to constructed a tabbed panel may be as follows − main=TabbedPanel() tab1=TabbedPanelItem(text=”Tab 1”) Label=Label(text=”Label”) tab1.add_widget(label) tab2=TabbedPanelItem(text=”Tab 2”) btn=Button(text=”Button”) tab2.add_widget(btn) main.add_widget(tab1) main.add_widget(tab2) The Tabbed panel can be further customized by tweaking a few properties − You can choose the position in which the tabs are displayed, by setting the tab_pos property to either of the values – left_top, left_mid, left_bottom, top_left, top_mid, top_right, right_top, right_mid, right_bottom, bottom_left, bottom_mid, bottom_right. Each tab has a special button TabbedPAnelHeader, containing a content property. The tabbed panel comes with a default tab, which you can get rid of, by setting do_default_tab to False. If the default tab is displayed, an on_default_tab event is provided for associating a callback − tp.bind(default_tab = my_default_tab_callback) Tabs and content can be removed in several ways − tp.remove_widget() removes the tab and its content. tp.clear_widgets() clears all the widgets in the content area. tp.clear_tabs() removes the TabbedPanelHeaders Example In the example below, we use two tabbed panels, first to display a simple registration form, and in the other, a login form. We shall us the “kv” language script to construct the design. The default tab is removed. The first tab holds a 2-column grid layout and contains labels and text input boxes for the user to enter his details, followed by a Submit button. The second tab also has a two-column grid, with provision to enter email and password by the registered user. TabbedPanel: size_hint: .8, .8 pos_hint: {”center_x”: .5, ”center_y”: .5} do_default_tab: False TabbedPanelItem: text:”Register Tab” GridLayout: cols:2 Label: text:”Name” size_hint:(.2, .1) pos_hint:{”x”:.2, ”y”:.75} TextInput: size_hint:(.4, .1) pos_hint:{”x”:.3, ”y”:.65} Label: text:”email” size_hint:(.2, .1) pos_hint:{”x”:.2, ”y”:.55} TextInput: size_hint:(.4, .1) pos_hint:{”x”:.3, ”y”:.45} Label: text:”Password” size_hint:(.2, .1) pos_hint:{”x”:.2, ”y”:.35} TextInput: password:True size_hint:(.4, .1) pos:(400, 150) pos_hint:{”x”:.3, ”y”:.25} Button: text:”Submit” size_hint : (.2, .1) pos_hint : {”center_x”:.5, ”center_y”:.09} TabbedPanelItem: text:”Login Tab” GridLayout: cols:2 Label: text:”email” size_hint:(.2, .1) pos_hint:{”x”:.2, ”y”:.55} TextInput: size_hint:(.4, .1) pos_hint:{”x”:.3, ”y”:.45} Label: text:”Password” size_hint:(.2, .1) pos_hint:{”x”:.2, ”y”:.35} TextInput: password:True size_hint:(.4, .1) pos:(400, 150) pos_hint:{”x”:.3, ”y”:.25} Button: text:”Submit” size_hint : (.2, .1) pos_hint : {”center_x”:.5, ”center_y”:.09} The App code utilizing the above “kv” script design is as follows − from kivy.app import App from kivy.core.window import Window Window.size = (720,300) class TabDemoApp(App): def build(self): pass TabDemoApp().run() Output When you run the above code, the app window shows the tabbed panel with the first tab contents exposed. Click the Login Tab to see the contents of the second tab. Print Page Previous Next Advertisements ”;