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.
Category: kivy
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 – Animation
Kivy – Animation ”; Previous Next Applying animation effects to a widget is one of the most attractive features of Kivy framework. In Kivy, the animation functionality is defined in Animation class included in kivy.animation module. The same module also includes AnimationTransition class. It is a collection of functions to apply animation transition effects. To use animation effect, the Kivy application should − First decide on which property of a widget to animate, Set up an object of Animation class, Set the final value of the property, Call the start() method of Animation object, passing the widget as an argument. To animate a Widget”s x or y position, simply specify the target x/y values where you want the widget positioned at the end of the animation − rom kivy.animation import Animation anim = Animation(x=100, y=100) anim.start(widget) This will animate the x and y positions of the widget from its original position to 100,100 taking by default a duration one second. You can ask for animating multiple properties. For example, to animate the position and size use − anim = Animation(x=50, size=(80, 80)) anim.start(widget) You can also specify a transition (or t) property of the Animation object to apply transition effects. Using the ”+” operator between two Animation objects joins the animations sequentially. anim = Animation(x=50) + Animation(size=(80, 80), duration=2) This will animate the widget to x=50 over 1 second, then animate the size to (80, 80) over the next two seconds. On the other hand, the ”&” operator joins animations in parallel. The following example will perform simultaneous animation of the position to (80, 10) over 1 second, the size to (800, 800) − anim = Animation(pos=(80, 10)) anim &= Animation(size=(800, 800), duration=2.) If the program is implementing ”sequence” animations, the animation can be set to be repeated in a loop by setting anim.repeat = True. The Animation class has the following properties and methods − duration or d − Duration of the animation, in seconds, defaults to 1. transition or t − Transition function for animate properties. It can be the name of a method from AnimationTransition. step or s − float. Step in milliseconds of the animation. Defaults to 0, which means the animation is updated for every frame. If you want to animate at 30 FPS, use s=1/30. cancel() − Cancel the animation previously applied to a widget. cancel_all() − Cancel all animations that concern a specific widget / list of properties. start() − Start the animation on a widget. stop() − Stop the animation previously applied to a widget, triggering the on_complete event. stop_all() − Stop all animations that concern a specific widget / list of properties. Example With the help of the following “kv” script, a button and a label are placed in a vertical box layout. The button is bound to animating() method. <MyLayout> BoxLayout: orientation: “vertical” size: root.width, root.height padding: 50 spacing: 20 Label: id: my_label text: “Hello World!” font_size: 32 Button: text: “Start” font_size: 32 size_hint: .5, .5 pos_hint: {“center_x”: 0.5} on_release: root.animating(self) This “kv” script is loaded in the App class. The animating() method applies position, background color and size animation effects on the button when clicked. from kivy.app import App from kivy.uix.widget import Widget from kivy.lang import Builder from kivy.animation import Animation from kivy.core.window import Window Window.size = (720, 400) class MyLayout(Widget): def animating(self, widget, *args): animate = Animation( pos=(widget.pos[0], Window.height – 50) ) animate += Animation(pos=(widget.pos[0], 0)) animate += Animation( background_color=(0, 0, 1, 1), duration=1 ) animate += Animation(size_hint=(1, 1)) animate += Animation(size_hint=(.5, .5)) animate += Animation(pos_hint={“center_x”: 0.1}) animate += Animation(pos_hint={“center_x”: 0.5}) animate.start(widget) # Create a callback animate.bind(on_complete=self.my_callback) def my_callback(self, *args): self.ids.my_label.text = “Hello Kivy” class AwesomeApp(App): def build(self): return MyLayout() if __name__ == ”__main__”: AwesomeApp().run() Output Run the above program. You should see a label and a button below it. Click the button to start the animation effects. The button moves up and down, left and right, grows and shrinks in size, and changes color. 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 ”;
Kivy – Touch Ripple
Kivy – Touch Ripple ”; Previous Next In the Kivy framework, the “Touch Ripple” is not really a widget or any concrete class. Instead, the TouchRippleBehavior mixin adds a touch ripple visual effect to a layout or an individual widget. Normally, Kivy has a default press/release visualization. This class adds the ripple effect from Google Material Design. This mixin class is defined in the “kivy.uix.behaviors.touchripple” module. from kivy.uix.behaviors.touchripple import TouchRippleBehavior The Ripple behavior does not trigger automatically. A concrete class needs to implement this behavior mixin and explicitly call ripple_show() respective ripple_fade() methods manually. To customize the ripple effects, use the following properties − ripple_duration_in − Animation duration taken to show the overlay. It”s a NumericProperty and defaults to 0.5. ripple_duration_out − A NumericProperty defaulting to 0.2 sets the animation duration taken to fade the overlay. ripple_fade_from_alpha − Alpha channel for ripple color the animation starts with. Default value is 0.5. ripple_fade_to_alpha − Alpha channel for ripple color the animation targets to, defaults to 0.8. ripple_rad_default − Default radius the animation starts from. It is a NumericProperty and defaults to 10. ripple_scale − Max scale of the animation overlay calculated from max(width/height) of the decorated widget. The ripple_show() method begins ripple animation on current widget. You need to pass a touch event as argument. The ripple_fade() method is called to finish ripple animation on current widget. The ripple_func_in and ripple_funcion_out are animation callbacks for showing and hiding the overlay. Example In the following example, we have used kv script that puts a label inside a grid layout, and processes the touch_down and touch_up events. The on_touch_down() method calls the ripple_show() method to generate ripple effect with a duration of 3 seconds. The on_touch_up() methods finishes the ripple effect by calling the ripple_fade() method. from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.uix.behaviors.touchripple import TouchRippleBehavior from kivy.core.window import Window Window.size = (720,300) class RippleLabel(TouchRippleBehavior, GridLayout): def __init__(self, **kwargs): super(RippleLabel, self).__init__(**kwargs) def on_touch_down(self, touch): collide_point = self.collide_point(touch.x, touch.y) if collide_point: touch.grab(self) self.ripple_duration_in=3 self.ripple_show(touch) return True return False def on_touch_up(self, touch): if touch.grab_current is self: touch.ungrab(self) self.ripple_duration_out=3 self.ripple_fade() return True return False class MyRippleApp(App): def build(self): return RippleLabel(cols=1) MyRippleApp().run() The “kv” script − <RippleLabel>: GridLayout: cols:1 Label: size:(root.width, root.height) pos_hint:{”center_x”:.5, ”center_y”:.5} text:”OK” font_size:100 color:(1,0,0,1) Output Run the program and click the “OK” label. It will produce ripple waves on the window surface. Increase the duration to see the effect. Print Page Previous Next Advertisements ”;
Kivy – Grid Layouts
Kivy – Grid Layouts ”; Previous Next GridLayout is one of the commonly used layout types in Kivy. A GridLayout object acts as a container grid. It divides the window area in specified number of rows and columns and puts other widgets in the cells. GridLayout class is defined in kivy.uix.gridlayout module. The object must have at least one of the properties – rows and cols – defined. If you do not specify any of these two, Kivy throws GridLayoutException. from kivy.uix.gridlayout import GridLayout grid = GridLayout(**kwargs) The properties of GridLayout object are as follows − cols − Number of columns in the grid. You can no longer set this to a negative value. cols is a NumericProperty and defaults to None. rows − Number of rows in the grid. You can no longer set this to a negative value. rows is a NumericProperty and defaults to None. cols_minimum − Dict of minimum width for each column. The dictionary keys are the column numbers, (e.g. 0, 1, 2…).It is a DictProperty and defaults to {}. rows_minimum − Dict of minimum height for each row. The dictionary keys are the row numbers, (e.g. 0, 1, 2…). It is a DictProperty and defaults to {}. 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. 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”. row_default_height − Default minimum size to use for row. row_default_height is a NumericProperty and defaults to 0. row_force_default − If True, ignore the height and size_hint_y of the child and use the default row height. row_force_default is a BooleanProperty and defaults to False. spacing −: Spacing between children: [spacing_horizontal, spacing_vertical]. spacing is a VariableListProperty and defaults to [0, 0]. padding − Padding between the layout box and its children: [padding_left, padding_top, padding_right, padding_bottom]. padding is a VariableListProperty and defaults to [0, 0, 0, 0]. By default, all the widgets have the same size. This is because the default size_hint is (1,1). def build(self): self.lo = GridLayout(cols=2) self.b1 = Button(text=”Button 1”, font_size=20) self.b2 = Button(text=”Button 2”, font_size=20) self.b3 = Button(text=”Button 3”, font_size=20) self.b4 = Button(text=”Button 4”, font_size=20) self.lo.add_widget(self.b1) self.lo.add_widget(self.b2) self.lo.add_widget(self.b3) self.lo.add_widget(self.b4) return self.lo With this code, you will get the following layout − Now, let”s fix the size of Hello buttons to 250px instead of using “size_hint_x=None”. self.lo = GridLayout(cols = 2) self.b1 = Button( text=”Button 1”, font_size=20, size_hint_x=None, width=250 ) self.b2 = Button(text=”Button 2”, font_size=20) self.b3 = Button( text=”Button 3”, font_size=20, size_hint_x=None, width=250 ) self.b4 = Button(text=”Button 4”, font_size=20 The App window appears as below − If we define row_default_height to 100 and set “row_force_default=True” − self.lo = GridLayout( cols=2, row_force_default=True, row_default_height=100 ) self.b1 = Button( text=”Button 1”, font_size=20, size_hint_x=None, width=250 ) self.b2 = Button(text=”Button 2”, font_size=20) self.b3 = Button( text=”Button 3”, font_size=20, size_hint_x=None, width=250 ) self.b4 = Button(text=”Button 4”, font_size=20) Now the window appears like this − Example 1 In this program, we add 15 buttons in a grid layout with four columns. The caption of each button is a unique but randomly generated number between 1 to 15. The randint() function in random module is used for this purpose. from kivy.app import App from kivy.uix.button import Button from kivy.uix.gridlayout import GridLayout from kivy.config import Config import random Config.set(”graphics”, ”width”, ”720”) Config.set(”graphics”, ”height”, ”400”) Config.set(”graphics”, ”resizable”, ”1”) class MyApp(App): def build(self): self.grid = GridLayout(cols = 4) nums=[] for i in range(1,16): while True: num = random.randint(1,15) if num not in nums: nums.append(num) self.grid.add_widget(Button(text = str(num))) break return self.grid if __name__ == ”__main__”: MyApp().run() Output When you run this code, it will produce the following output window − Example 2 The GridLayout in Kivy doesn”t have the provision to span a widget across rows and/or columns. It is also not possible to place a widget by its row and column numbers. It is required to arrange a few labels and text input boxes in a two column grid, but the submit button below should span across two columns. To achieve this, we place a 2 column grid inside a on column grid, and a button below it. 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.gridlayout import GridLayout from kivy.core.window import Window Window.size = (720, 400) class DemoApp(App): def build(self): self.grid = GridLayout(rows=2) self.top_grid = GridLayout( cols=2, row_force_default=True, row_default_height=100 ) self.top_grid.cols = 2 self.top_grid.add_widget( Label(text=”Name: “, size_hint_x=None, width=250) ) self.fname = TextInput( multiline=False, size_hint_x=None, width=650 ) self.top_grid.add_widget(self.fname) self.top_grid.add_widget(Label(text=”Address: “)) self.address = TextInput(multiline=True) self.top_grid.add_widget(self.address) self.top_grid.add_widget(Label(text=”College: “)) self.college = TextInput(multiline=False) self.top_grid.add_widget(self.college) self.grid.add_widget(self.top_grid) self.b1 = Button(text=”Submit”, size_hint_y=None, height=200) self.grid.add_widget(self.b1) return self.grid if __name__ == ”__main__”: DemoApp().run() Output When you