Kivy – Text Input

Kivy – Text Input ”; Previous Next You often see a rectangular box being used in desktop and web applications, meant for the user to enter some text. A textbox is an essential widget in any GUI toolkit. In Kivy, the TextInput provides a control in which the user can enter and edit text. The TextInput control can be customized to receive a single line or multiline text. A certain part of the text can be selected with mouse. One can also perform full screen editing inside it with the cursor movement. The TextInput class is defined in kivy.uix.textinput module. from kivy.uix.textinput import TextInput textbox = TextInput(**kwargs) Following properties are defined in the TextInput class − allow_copy − Decides whether to allow copying the text. allow_copy is a BooleanProperty and defaults to True. background_color − Current color of the background, in (r, g, b, a) format.It is a ColorProperty and defaults to [1, 1, 1, 1] (white). border − Border used for BorderImage graphics instruction. Used with background_normal and background_active. Can be used for a custom background. It must be a list of four values: (bottom, right, top, left). border is a ListProperty and defaults to (4, 4, 4, 4). cursor − Tuple of (col, row) values indicating the current cursor position. You can set a new (col, row) if you want to move the cursor. The scrolling area will be automatically updated to ensure that the cursor is visible inside the viewport. cursor is an AliasProperty. cursor_color − Current color of the cursor, in (r, g, b, a) format. cursor_color is a ColorProperty and defaults to [1, 0, 0, 1]. cut() − Copy current selection to clipboard then delete it from TextInput. delete_selection(from_undo=False) − Delete the current text selection (if any). disabled_foreground_color − Current color of the foreground when disabled, in (r, g, b, a) format. disabled_foreground_color is a ColorProperty and defaults to [0, 0, 0, 5] (50% transparent black). font_name − Filename of the font to use. The path can be absolute or relative. Relative paths are resolved by the resource_find() function. font_name − is a StringProperty and defaults to ”Roboto”. This value is taken from Config. font_size − Font size of the text in pixels. font_size is a NumericProperty and defaults to 15 sp. foreground_color − Current color of the foreground, in (r, g, b, a) format. oreground_color is a ColorProperty and defaults to [0, 0, 0, 1] (black). halign − Horizontal alignment of the text. halign is an OptionProperty and defaults to ”auto”. Available options are : auto, left, center and right. hint_text − Hint text of the widget, shown if text is ””. hint_text a AliasProperty and defaults to ””. hint_text_color − Current color of the hint_text text, in (r, g, b, a) format, ColorProperty and defaults to [0.5, 0.5, 0.5, 1.0] (grey). input_filter − Filters the input according to the specified mode, if not None. If None, no filtering is applied. It is an ObjectProperty and defaults to None. Can be one of None, ”int” (string), or ”float” (string), or a callable. insert_text(substring, from_undo=False) − Insert new text at the current cursor position. Override this function in order to pre-process text for input validation. line_height − Height of a line. This property is automatically computed from the font_name, font_size. Changing the line_height will have no impact. line_height is a NumericProperty, read-only. line_spacing − Space taken up between the lines. line_spacing is a NumericProperty and defaults to 0. minimum_height − Minimum height of the content inside the TextInput. minimum_height is a readonly AliasProperty. multiline − If True, the widget will be able show multiple lines of text. If False, the “enter” keypress will defocus the textinput instead of adding a new line on_touch_down(touch) − Receive a touch down event. The touch parameter is object of MotionEvent class. It returns bool If True, the dispatching of the touch event will stop. If False, the event will continue to be dispatched to the rest of the widget tree. on_touch_move(touch) − Receive a touch move event. The touch is in parent coordinates. on_touch_up(touch) − Receive a touch up event. The touch is in parent coordinates. padding − Padding of the text: [padding_left, padding_top, padding_right, padding_bottom]. Padding also accepts a two argument form [padding_horizontal, padding_vertical] and a one argument form [padding]. Padding is a VariableListProperty and defaults to [6, 6, 6, 6]. password − If True, the widget will display its characters as the character set in password_mask. password_mask − Sets the character used to mask the text when password is True. password_mask is a StringProperty and defaults to ”*”. paste() − Insert text from system Clipboard into the TextInput at current cursor position. readonly − If True, the user will not be able to change the content of a textinput. select_all() − Select all of the text displayed in this TextInput. select_text(start, end) − Select a portion of text displayed in this TextInput. Parameters are start – Index of textinput.text from where to start selection and end – Index of textinput.text till which the selection should be displayed selection_color − Current color of the selection, in (r, g, b, a) format. selection_from − If a selection is in progress or complete, this property will represent the cursor index where the selection started. selection_text − Current content selection. selection_text is a StringProperty and defaults to ””, readonly. tab_width − By default, each tab will be replaced by four spaces on the text input widget. You can set a lower or higher value. tab_width is a NumericProperty and defaults to 4. text − Text of the widget. It is an AliasProperty. Usage To create a simple hello world − widget = TextInput(text=”Hello world”) If you want

Kivy – Spelling

Kivy – Spelling ”; Previous Next Kivy library comes with a spelling module in its “kivy.core” package. It provides abstracted access to a range of spellchecking backends as well as word suggestions. The API is inspired by the “python-enchant” library. You need to install enchant to be able to use this feature. pip3 install pyenchant Example Create an object of Spelling class (defined in “kivy.core.spelling” module) to call its various methods. For instance, the list_languages() method returns a list of supported languages. from kivy.core.spelling import Spelling s = Spelling() s.list_languages() Output It will list down all the supported languages − [”en_BW”, ”en_AU”, ”en_BZ”, ”en_GB”, ”en_JM”, ”en_DK”, ”en_HK”, ”en_GH”, ”en_US”, ”en_ZA”, ”en_ZW”, ”en_SG”, ”en_NZ”, ”en_BS”, ”en_AG”, ”en_PH”, ”en_IE”, ”en_NA”, ”en_TT”, ”en_IN”, ”en_NG”, ”en_CA”] You can select a specific language from the list for subsequent use. s.select_language(”en_US”) The check() method in the Spelling class checks if a given word is valid in the currently active language. If yes, it returns True. If the word shouldn”t be checked, returns None (e.g. for ””). If it is not a valid word in self._language, then it returns False. >>> s.check(”this”) True >>> s.check(”thes”) False You can obtain suggestions from the Spelling class for a given word. s.suggest(”wold”) [”wild”, ”wolf”, ”old”, ”wolds”, ”woald”, ”world”, ”would”, ”weld”, ”sold”, ”woad”, ”word”, ”told”, ”wood”, ”cold”, ”gold”] If you try to select a language which is not present in the list of supported language, Kivy raises the following NoSuchLangError exception − s.select_language(”Hindi”) kivy.core.spelling.NoSuchLangError: Enchant Backend: No language for “Hindi” When a language-using method is called but no language was selected prior to the call, Kivy raises “NoLanguageSelectedError”. Print Page Previous Next Advertisements ”;

Kivy – Relative Layout

Kivy – Relative Layout ”; Previous Next The behavior of Relative Layout is very similar to that of FloatLayout. The main difference between the two is that positioning coordinates of child widgets in a relative layout are relative to the layout size and not the window size as is the case of float layout. To understand what it means, consider the following UI designed with FloatLayout. When you resize the window, because of the absolute positioning in float layout, the placement of widgets is not proportional to the resized window. As a result, the interface design is not consistent. The relative layout doesn”t have such effect because the size and position of widgets is relative to the layout. When a widget with position (0,0) is added to a RelativeLayout, the child widget will also move when the position of the RelativeLayout is changed. Coordinates of the child widgets are always relative to the parent layout. The RelativeLayout class is defined in the “kivy.uix.relativelayout” module. from kivy.uix.relativelayout import RelativeLayout rlo = RelativeLayout(**kwargs) Example The following code assembles labels, text boxes and a submit button in RelativeLayout. from kivy.app import App from kivy.uix.label import Label from kivy.uix.button import Button from kivy.uix.textinput import TextInput from kivy.uix.relativelayout import RelativeLayout from kivy.core.window import Window Window.size = (720, 400) class RelDemoApp(App): def build(self): rlo = RelativeLayout() l1 = Label( text=”Name”, size_hint=(.2, .1), pos_hint={”x”: .2, ”y”: .75} ) rlo.add_widget(l1) t1 = TextInput( size_hint=(.4, .1), pos_hint={”x”: .3, ”y”: .65} ) rlo.add_widget(t1) l2 = Label( text=”Address”, size_hint=(.2, .1), pos_hint={”x”: .2, ”y”: .55} ) rlo.add_widget(l2) t2 = TextInput( multiline=True, size_hint=(.4, .1), pos_hint={”x”: .3, ”y”: .45} ) rlo.add_widget(t2) l3 = Label( text=”College”, size_hint=(.2, .1), pos_hint={”x”: .2, ”y”: .35} ) rlo.add_widget(l3) t3 = TextInput( size_hint=(.4, .1), pos=(400, 150), pos_hint={”x”: .3, ”y”: .25} ) rlo.add_widget(t3) b1 = Button( text=”Submit”, size_hint=(.2, .1), pos_hint={”center_x”: .5, ”center_y”: .09} ) rlo.add_widget(b1) return rlo RelDemoApp().run() Output When the above code is executed, the application window shows the UI as follows − Note that unlike in the case of FloatLayout, resizing the window doesn”t alter the proportional sizing and positioning of the widgets. “kv” design language script The “kv” file for producing the above UI instead of build() method in the App class is as follows − RelativeLayout: 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:”Address” size_hint:(.2, .1) pos_hint:{”x”:.2, ”y”:.55} TextInput: multiline:True size_hint:(.4, .1) pos_hint:{”x”:.3, ”y”:.45} Label: text:”College” size_hint:(.2, .1) pos_hint:{”x”:.2, ”y”:.35} TextInput: 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} 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 – Layouts

Kivy – Layouts ”; Previous Next The Kivy application window holds one widget at a time. Hence, if you try to add two buttons, only the second will be displayed. On the other hand, a good GUI needs different widgets i.e. labels, text input boxes, buttons etc. to be ergonomically placed. For this purpose, Kivy framework provides layouts. Layout itself is a widget capable of holding other widgets inside it. Layout therefore is called as a container widget In Kivy, different types of layout containers are available. All of them implement Layout interface, defined in the “kivy.uix.layout” module. The Layout interface itself inherits the Widget class. Two of the most important methods of this interface are − add_widget() remove_widget() add_widget() This method is used to Add a new widget as a child of this layout. Its syntax is like this − add_widget(self, widget, *args, **kwargs) Parameters widget − Widget to add to our list of children. index − index to insert the widget in the list. Notice that the default of 0 means the widget is inserted at the beginning of the list and will thus be drawn on top of other sibling widgets. canvas − Canvas to add widget”s canvas to. Can be ”before”, ”after” or None for the default canvas. remove_widget This method is used to remove a widget from the children of this widget. Here is its syntax − remove_widget(self, widget, *args, **kwargs) Where, the parameter “widget” stands for the widget that is to be removed from the children list. Note that Layout is an interface, and hence it can not be used directly. The Layout classes that implement these methods are the concrete classes as in the following list − Sr.No Methods & Description 1 AnchorLayout Widgets can be anchored to the ”top”, ”bottom”, ”left”, ”right” or ”center”. 2 BoxLayout Widgets are arranged sequentially, in either a ”vertical” or a ”horizontal” orientation. 3 FloatLayout Widgets are essentially unrestricted. 4 RelativeLayout Child widgets are positioned relative to the layout. 5 GridLayout Widgets are arranged in a grid defined by the rows and cols properties. 6 PageLayout Used to create simple multi-page layouts, in a way that allows easy flipping from one page to another using borders. 7 ScatterLayout Widgets are positioned similarly to a RelativeLayout, but they can be translated, rotated and scaled. 8 StackLayout Widgets are stacked in a lr-tb (left to right then top to bottom) or tb-lr order. In the subsequent chapters, we shall discuss each of these layouts in detail with relevant examples. Print Page Previous Next Advertisements ”;

Kivy – Configuration Object

Kivy – Configuration Object ”; Previous Next When Kivy software is installed, it creates a configuration file that contains various parameter with their default values. The file, named as “config.ini”, is stored in a directory identified by KIVY_HOME environment variable. On Windows: The file is stored at C:Usersuser.kivyconfig.ini. On Linux: /home/user/.kivy/config.ini. On macOS: /Users/user/.kivy/config.ini. On Android: /data/data/org.kivy.launcher/files/.kivy/config.ini. On iOS: <HOME_DIRECTORY>/Documents/.kivy/config.ini. In order to change the default settings, you can alter this file manually or use the Config object. The Config object”s read(), set() and write() methods are provided to read the value of a setting, assign a new value and write the changes to the configuration file. from kivy.config import Config Config.read(<file>) Config.write() # set config You can also assign a value to any configuration parameter (called token) in effect only for the current session, by setting environment variable – either programmatically or from the OS terminal. To set an environment variable from Python − import os os.environ[”KIVY_LOG_MODE”] = MIXED” You can also set an environment variable from OS terminal. In Windows command prompt terminal − set KIVY_LOG_MODE = MIXED” On Linux/MacOS − export KIVY_LOG_MODE = MIXED” The configuration file config.ini consists of one or more sections, and each section consists of parameters called tokens. A typical “config.ini” file for KIvy installation consists of secions such as Kivy, Graphics, widgets, etc. To change a certain configuration setting with the environment variable, use the following instruction format − KCFG_<section>_<key> = <value> For example, to set the log level − KCFG_KIVY_LOG_LEVEL= “warning” The same can be done programmatically with following syntax − os.environ[“KCFG_KIVY_LOG_LEVEL”] = ” warning” Configuration Tokens The configuration file is divided in several sections, and each section consists of tokens or parameters. Here are some important tokens given in section-wise order − Section – [Kivy] default_font − Default fonts used for widgets displaying any text. desktop − int, 0 or 1. This option controls features, such as enabling or disabling drag-able scroll-bar in scroll views, disabling of bubbles in TextInput, etc. log_dir − Path of log directory. log_level − string, one of ”trace”, ”debug”, ”info”, ”warning”, ”error” or ”critical”. Set the minimum log level to use. Section – [postproc] double_tap_distance − Maximum distance allowed for a double tap, normalized inside the range 0 – 1000. double_tap_time − Time allowed for the detection of double tap, in milliseconds. triple_tap_distance − fMaximum distance allowed for a triple tap, normalized inside the range 0 – 1000. triple_tap_time − Time allowed for the detection of triple tap, in milliseconds. Section [graphics] fullscreen − one of 0, 1, ”fake” or ”auto”. height − Height of the Window, not used if fullscreen is set to auto. left − Left position of the Window. top − Top position of the Window. resizable − one of 0 or 1 – 0 for fixed size and 1 for resizable. width − Width of the Window, not used if fullscreen is set to auto. Section [widgets] scroll_distance − Default value of the scroll_distance property used by the ScrollView widget. scroll_timeout − Default value of the scroll_timeout property used by the ScrollView widget. Methods of Config Object add_section() − Add a section to the configuration if the section is missing. For example − Config.add_section(”newsection”) get() − Get an option value for a given section. For example − Config.get(”graphics”, ”width”) set() − assign value to a configuration token. Example − Config.set(”graphics”, ”width”, 720) write() − Write the configuration to the last file opened using the read() method. It returns True if the write finished successfully, False otherwise. Print Page Previous Next Advertisements ”;

Kivy – Quick Guide

Kivy – Quick Guide ”; Previous Next Kivy – Getting Started 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. Kivy – Installation 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.