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 ”;

Kivy – Anchor Layout

Kivy – Anchor Layout ”; Previous Next When this layout is used, we can arrange a widget inside it in such a way that it is anchored to a certain position of the layout”s dimensions. The AnchorLayout class is defined in the “kivy.uix.anchorlayout” module. from kivy.uix.anchorlayout import AnchorLayout lo = AnchorLayout(**kwargs) Keyword Parameters anchor_x − Defines the horizontal anchor for the widget to be placed. It is an OptionProperty, whose value must be from ”left”, ”center” or ”right”. Default is ”center”. anchor_y − Defines the vertical anchor for the widget to be placed. It is an OptionProperty, whose value must be from ”top”, ”center” or ”bottom”. Default is ”center”. padding − Padding between the widget box and its children, in pixels: [padding_left, padding_top, padding_right, padding_bottom]. It also accepts a two-argument form [padding_horizontal, padding_vertical] and a one argument form [padding]. padding is a VariableListProperty and defaults to [0, 0, 0, 0]. The AnchorLayout class inherits the two methods “add_widget()” and “remove_widget()” which we have already covered in the earlier chapters. Example 1 The following example shows a typical use of AnchorLayout − from kivy.app import App from kivy.uix.label import Label from kivy.uix.anchorlayout import AnchorLayout from kivy.core.window import Window Window.size = (720, 400) class DemoApp(App): def build(self): lo = AnchorLayout( anchor_x=”left”, anchor_y=”bottom” ) self.l1 = Label( text=”Hello World”, font_size=20, size_hint=(None, None), size=(200, 75) ) lo.add_widget(self.l1) return lo if __name__ == ”__main__”: DemoApp().run() Output It can be seen that the label has been anchored to the left-bottom corner of the layout. The Kivy application with AnchorLayout can also be built with the “kv” language script − AnchorLayout: anchor_x : ”left” anchor_y : ”bottom” Label: id:l1 text: ”Hello World” font_size: ”20pt” size_hint : (None, None) size : (200, 75) Example 2 In the example below, the application window has a top level GridLayout with widgets to be arranged in 3 rows. In each row, we put three AnchorLayouts such that the window contains nine anchor layouts with lefttop, left-center, left-bottom, center-top, center-center, center-bottom, right-top, right-center and right-bottom anchor-x and anchor-y properties. In each layout, a button widget is placed as per the anchor configuration. from kivy.app import App from kivy.uix.button import Button from kivy.config import Config from kivy.uix.anchorlayout import AnchorLayout from kivy.uix.gridlayout import GridLayout Config.set(”graphics”, ”width”, ”720”) Config.set(”graphics”, ”height”, ”400”) Config.set(”graphics”, ”resizable”, ”1”) class AnchorApp(App): def build(self): lo = GridLayout(rows=3) ax = [”left”, ”center”, ”right”] ay = [”top”, ”center”, ”bottom”] c = 0 # 3X3 grid with anchor layout in each for i in range(3): for j in range(3): print(ax[i], ay[j]) anchrlo = AnchorLayout( anchor_x=ax[i], anchor_y=ay[j] ) b = Button( text=ax[i] + “-” + ay[j], size_hint=(None, None), size=(200, 75), halign=ax[i] ) # red text color for top row, # green for middle row, # blue for bottom row if i == 0: b.color = [1, 0, 0, 1] if i == 1: b.color = [0, 1, 0, 1] if i == 2: b.color = [0, 0, 1, 1] anchrlo.add_widget(b) lo.add_widget(anchrlo) return lo AnchorApp().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.

Kivy – Stack Layout

Kivy – Stack Layout ”; Previous Next An object of StackLayout class acts as a widget container, wherein the children widgets are placed one besides other, either horizontally or vertically, depending upon the orientation property. As many widgets are accommodated as the layout dimensions can fit. The dimensions of each widget can be varying. Let us assume that the StackLayout object is configured to hold the widgets from left to right and from top to bottom. After putting “x” widgets horizontally, if it is not possible to put the widget “x+1” in the same row, it is pushed to the next row, and so on till the height of the layout exhausts. The StackLayout class is defined in the “kivy.uix.stacklayout” module. from kivy.uix.stacklayout import StackLayout stack = StackLayout(**kwargs) The StackLayout object is customized by defining following properties − minimum_width − Automatically computed minimum width needed to contain all children. It is a NumericProperty and defaults to 0. It is read only. minimum_height − Automatically computed minimum height needed to contain all children. It is a NumericProperty and defaults to 0. It is read only. minimum_height − Automatically computed minimum height needed to contain all children. The minimum_height is a NumericProperty and defaults to 0. It is read only. minimum_size − Automatically computed minimum size needed to contain all children.minimum_size is a ReferenceListProperty of (minimum_width, minimum_height) properties. It is read only. minimum_width − Automatically computed minimum width needed to contain all children. minimum_width is a NumericProperty and defaults to 0. It is read only. orientation − Orientation of the layout. This property determines how the widgets are placed in successive cells in the grid. orientation is an OptionProperty. Its valid values are − ”lr-tb” − cells filled in left to right and top to bottom order. ”tb-lr” − cells filled in top to bottom and left to right order. ”rl-tb” − cells filled in right to left and top to bottom order. ”tb-rl” − cells filled in top to bottom and right to left order. ”lr-bt” − cells filled in left to right and bottom to top order. ”bt-lr” − cells filled in bottom to top and left to right order. ”rl-bt” − cells filled in right to left and bottom to top order. ”bt-rl” − cells filled in bottom to top and right to left order. Default value of orientation property is ”lr-tb”. Example The following program demonstrates the use of StackLayout. As mentioned earlier, the default orientation is ”lr-tb”. Buttons of progressively increasing width but same height are placed from left to right and then top to bottom order. As and when the next button can not fit in current row, it is pushed down. Each button is captioned with a randomly generated unique number between 1 to 50. from kivy.app import App from kivy.uix.button import Button from kivy.config import Config from kivy.uix.stacklayout import StackLayout import random Config.set(”graphics”, ”width”, ”720”) Config.set(”graphics”, ”height”, ”400”) Config.set(”graphics”, ”resizable”, ”1”) class StackApp(App): def build(self): stack = StackLayout() width=100 nums=[] for i in range(1, 25): while True: num = random.randint(1,25) if num not in nums: nums.append(num) btn = Button( text = str(num), width=width, size_hint=(None, 0.15) ) width = width+num*2 stack.add_widget(btn) break return stack StackApp().run() Output It will produce a stack layout like the one shown below − If you try to resize the window, the position of the buttons will change accordingly and they are either be accommodated in the row above, or pushed down. Let us change the orientation of the layout to ”tb-lr”. stack = StackLayout(orientation=”tb-lr”) Run the program again and see the change − Again, change the orientation property to ”rl-bt” and run the program − stack = StackLayout(orientation=”rl-bt”) The layout starts populating buttons from right to left and bottom to right. As a result, the resulting window appears as below − Print Page Previous Next Advertisements ”;

Kivy – Garden

Kivy – Garden ”; Previous Next Kivy Garden is a repository of Kivy widgets developed by individual users. It is a project maintained by the users and its aim is to centralize the addons for Kivy. The user contributed Kivy packages are hosted on Kivy Garden repository https://github.com/kivy-garden. The widgets developed by users and uploaded to the Garden repository are called Flowers. The flowers in Kivy Garden are of two types. Those before Kivy version 1.11.0 are the legacy flowers. To install the legacy flower widgets you need to use the command − garden install flower-name The legacy flowers are not the proper Python packages, and are named with garden prefix attached to it. For example, a widget used as a Matplotlib backend for Kivy is garden.matplotlib. On the other hand, the new flowers are Python packages which are hosted on PyPI repository and therefore installed with the regular pip utility. pip install flower The modern Kivy flowers are not having the garden prefix. For example the mapview widget provides a container for displaying interactive maps in a Kivy app. pip install mapview You can install master directly from github. For example, the following command installs the graph flower − python -m pip install https://github.com/kivy-garden/graph/archive/master.zip Example Let us use the mapview flower in a Kivy application − from kivy_garden.mapview import MapView from kivy.app import App from kivy.core.window import Window Window.size = (720,400) class MapViewApp(App): def build(self): mapview = MapView(zoom=11, lat=50.6394, lon=3.057) return mapview MapViewApp().run() Output When you run this code, it will produce the following output window − Print Page Previous Next Advertisements ”;

Kivy – Text

Kivy – Text ”; Previous Next The “kivy.core.text” module in Kivy library acts as a backend layer for rendering text. However, it should be used only if the “kivy.uix.label.Label” widget is not giving satisfactory result. This module has two important uses: one is to derive the texture from the core Label object and apply it to any widget in the application, and second is apply custom fonts to the text property of widgets like label, button or Text input (or any widget with text property) Using Texture The Label widget (in “kivy.uix.label” module) is often not efficient in loading in the memory. To overcome this, the approach is to have an object of core.label class, and use its texture with the conventional widget. First import the Label class from “kivy.core.label” (to avoid confusion, name it as CoreLabel). from kivy.core.text import Label as CoreLabel cl=CoreLabel(text=”Hi there!”, font_size=50, color=(1, 0, 0, 1)) Call the refresh() method on this object to compute things and generate the texture. cl.refresh() Obtain the texture and the texture size. texture = cl.texture texture_size = list(texture.size) This can now be used with any widget now. Example In the following code, we add a label widget to a vertical box layout and use the texture of a core level object with it. from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.graphics import * from kivy.core.text import Label as CoreLabel from kivy.uix.label import Label from kivy.uix.widget import Widget from kivy.core.window import Window Window.size = (720,400) class CoreLabelApp(App): def build(self): cl=CoreLabel(text=”Hi there!”, font_size=50, color=(1, 0, 0, 1)) cl.refresh() texture = cl.texture main=BoxLayout(orientation=”vertical”) l=Label() texture_size = list(texture.size) l.canvas.add(Rectangle(texture=texture, size=texture_size)) main.add_widget(l) return main CoreLabelApp().run() Output It will produce the following output − Custom Fonts All the widgets that have a text property are rendered with a default set of fonts as per the settings in the config.ini file of Kivy installation. default_font = [”Roboto”, ”data/fonts/Roboto-Regular.ttf”, ”data/fonts/Roboto-Italic.ttf”, ”data/fonts/Roboto-Bold.ttf”, ”data/fonts/Roboto-BoldItalic.ttf”] However, you may want to use a specific font in which a text on any widget, it may be a label, or a TextInput box or a button. To do that, you need to download the relevant font file (The True Type Fonts are represented by .ttf files) and place it in the application folder. To make these fonts available for our application, they must be registered with the application. The register() method of the LabelBase class is invoked for the purpose. LabelBase is an abstract class used by the specific font renderer used by your operating system. The register() is a static method with following parameters − register(name, fn_regular, fn_italic=None, fn_bold=None, fn_bolditalic=None) where “name” is the font name with which you will refer the font in your program, and “fn_regular” parameter is the TTF file of the font. Download the TTF files for Consolas font and Monotype Corsiva font and store them in the application folder. Example In the following program, we are showing the same string in three text input boxes. The first box renders the text in the default font. The second box uses Monotype Corsiva and the third box applies the Consolas font. from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.uix.textinput import TextInput from kivy.core.text import LabelBase from kivy.core.window import Window Window.size = (720,400) class CustomFontApp(App): def build(self): main=GridLayout(cols=1) LabelBase.register(name=”font1”, fn_regular=”consolas.ttf”) LabelBase.register(name=”font2”, fn_regular=”MonotypeCorsivaFont.ttf”) txt=”Simple Is Better Than Complicated” t1=TextInput(text=txt, halign=”center”, font_size=48) t2=TextInput( text=txt, halign=”center”, font_name=”font2”, font_size=48 ) t3=TextInput( text=txt, halign=”center”, font_name=”font1”, font_size=48 ) main.add_widget(t1) main.add_widget(t2) main.add_widget(t3) return main CustomFontApp().run() Output It will produce the following output window − Print Page Previous Next Advertisements ”;

Kivy – Round Buttons

Kivy – Round Buttons ”; Previous Next All the widgets in Kivy framework are rectangular in shape. A button object always has right-angled corners. Hence, creating buttons with rounded corners doesn”t have a straightforward solution, however we can achieve it by a couple of tricks. Using Image as a Button We can define a class which extends ButtonBehavior mixin and Image class. Using any photo editor, create an elliptical shape looking like a round button, and use it as source property of Image object. You can override the on_press() method of ButtonBehavior class that lets the image be used as a button. from kivy.uix.behaviors import ButtonBehavior from kivy.uix.image import Image class imgbtn(ButtonBehavior, Image): def __init__(self, **kwargs): super(imgbtn, self).__init__(**kwargs) self.source = ”hello.png” self.pos_hint= {”center_x”:.5, ”center_y”:.6} def on_press(self): print(“Button pressed”) We can now use imgbtn object in a Kivy App. KivyMD Buttons Using KivyMD extension, we can design more attractive interfaces. KivyMD is a collection of Material Design widgets, to be used in a Kivy app. The KivyMD library provides different button objects with rounded corners. MDRoundFlatButton MDRoundFlatIconButton MDFillRoundFlatButton MDFillRoundFlatIconButton First, install the KivyMD extension (ensure that Kivy framework is installed earlier) pip3 install KivyMD The App class must be a subclass of MDApp class instead of App class. In this example, we will use MDRoundFlatButton class. Most of its properties are the same as Kivy Button. from kivymd.app import MDApp from kivymd.uix.button import MDRoundFlatButton btn = MDRoundFlatButton( text= ”Hello Python”, font_size= 20, size_hint= (.3, .1), pos_hint= {”center_x”:.5, ”center_y”:.3}, line_width=3 ) Example In the following example, we have a MDApp class. The build() method puts an image button and a MDRoundButton object in the application window. from kivymd.app import MDApp from kivy.core.window import Window from kivy.uix.floatlayout import FloatLayout from kivy.uix.image import Image from kivy.uix.behaviors import ButtonBehavior from kivymd.uix.button import MDRoundFlatButton Window.size = (720, 300) class imgbtn(ButtonBehavior, Image): def __init__(self, **kwargs): super(imgbtn, self).__init__(**kwargs) self.source = ”btnnormal.png” self.pos_hint= {”center_x”:.5, ”center_y”:.6} def on_press(self): print(“Button pressed”) class ButtonApp(MDApp): def build(self): flo = FloatLayout() self.btn1 = imgbtn() self.btn2 = MDRoundFlatButton( text= ”Hello Python”, font_size= 20, size_hint= (.3, .1), pos_hint= {”center_x”:.5, ”center_y”:.3}, line_width=3 ) flo.add_widget(self.btn1) flo.add_widget(self.btn2) return flo if __name__ == ”__main__”: ButtonApp().run() Output Run the application. You should get the following output, having rounded buttons. Using Canvas In Kivy, canvas is the root object for drawing by a widget. To simulate a Label to work as a circular button, we define a class that extends ButtonBehavior and a Label. The “kv” file defines the structure of this object as − <RoundCorneredButton>: canvas: Color: rgb: (1, 0, 0, 1) if self.state == ”normal” else (0, 0, 0, 1) RoundedRectangle: size: (self.size) pos: (self.pos) radius: [200, ] on_release: print(“This is the button made up by the canvas”) The class definition is as follows − class RoundCorneredButton(ButtonBehavior, Label): pass Example We shall use the above class and the kv design in the following App code − from kivy.app import App from kivy.uix.label import Label from kivy.config import Config from kivy.uix.button import ButtonBehavior from kivy.graphics import Rectangle, Color # Configuration Config.set(”graphics”, ”width”, ”720”) Config.set(”graphics”, ”height”, ”300”) Config.set(”graphics”, ”resizable”, ”1”) from kivy.app import App class RoundCorneredButton(ButtonBehavior, Label): pass class HelloApp(App): def build(self): return RoundCorneredButton() HelloApp().run() Output Run the code now. You will get a button with a circular shape, as shown here − Print Page Previous Next Advertisements ”;

Kivy – Action Bar

Kivy – Action Bar ”; Previous Next Kivy framework provides ActionBar widget, which acts as an easy to access menu, usually towards top or bottom of the application window, somewhat similar to ActionBar in Android. The ActionBar class is defined in kivy.uix.actionbar module. The appearance of an action bar depends on the composition of ActionView inside it. The ActionView holds one or more ActionButtons, represented by appropriate text caption and/or icon. The ActionView contains ActionButtons, separators, or ActionGroup. ActionGroup is a collection of ActionButtons. When you click the ActionGroup caption, the buttons are shown in a dropdown. When the ActionBar area becomes too small to accommodate all the contents, widgets are moved into the ActionOverflow area. You may want to display some ActionItems always on the ActionBar, irrespective of the number of items present. If you set the Important property of the ActionButton to True, it will get a priority placement on the bar. Example The code given below puts a label and an ActionBar at the bottom of the app window. The ActionBar displays a couple of ActionButtons, the “on_press” event of each updates the label caption to its own text property. The App code consists of the myActionApp class, whose build method constructs the appearance of the window by loading the associated kv file script. The Python code is shown below − from kivy.app import App from kivy.uix.widget import Widget from kivy.core.window import Window Window.size = (720,400) class mywidget(Widget): def pressed(self, obj): self.ids.l1.text=obj.text class myActionApp(App): def build(self): return mywidget() myActionApp().run() Here, mywidget class subclasses Widget class. Following kv language script, to be saved as myAaction.kv, composes the ActionBar with two buttons. It also places a label to show the caption of the ActionButton pressed. <mywidget> Label: id:l1 text:”Hello” pos_hint:{”center_x”:.5, ”center_y”:1} pos:(root.width/2-150, root.height/2-50) font_size:48 size:(300,100) ActionBar: size:root.width, 50 pos_hint: {”top”:1} background_color: .6, 4, .2, .6 ActionView: use_separator: True ActionPrevious: title: ”Action Bar” with_previous: False ActionOverflow: ActionButton: icon: ”atlas://data/images/defaulttheme/audio-volume-high” ActionButton: important: True text: ”Important” on_press:root.pressed(self) ActionButton: text: ”Btn1” on_press:root.pressed(self) Output Print Page Previous Next Advertisements ”;