Kivy – Language

Kivy – Language ”; Previous Next This chapter explains the important features, syntax and the usage of Kivy”s Design Language. The Kivy language (also know as “kv” Language) mainly describes the user interface of a Kivy app. It is similar to Qt”s QML. The rule definitions in the “kv” language are similar to CSS rules. Purpose The layout and placement of widgets in a Kivy app are coded into the build() method of Kivy”s App class. For applications with simpler user interface, this may work well. However, with the increasing complexity of the layout design, it quickly becomes too verbose and too difficult to maintain. Hence there is a need to separate the design part of the application from the processing logic. The “kv” language helps in achieving this separation of concerns. With the “kv” language script, you can create your widget tree in a declarative way and bind the widget properties to callbacks in a much more natural manner. One of the drawbacks of programmatically designing the interface is that the appearance cannot be viewed until the application is executed. On the other hand, the kviewer utility provides an interactive view of the design and placement of widgets, without having to load the script in the application. Loading the “kv” Script Once the design of widgets is finalized, it is loaded in the App class. This can be done in two ways. Using the Naming Convention Save the “kv” script with a “.kv” extension and its name corresponding to the name of App class. If the App class name ends with app keyword, it must be omitted. For example, if the App class is named as DemoApp as below, Class DemoApp(App): … … Then the kv file should be named as demo.kv. Kivy automatically loads the design into the build() method of the App class. If the kv file defines a root Widget, it will be attached to the App”s root attribute and used as the base of the application widget tree. Using the Builder Class If the name of the “kv” file doesn”t follow the above convention, the script can be loaded into the app with load_file() method of Loader class, which is available in the “kivy.lang” module. from kivy.app import App from kivy.lang import Builder Builder.load_file(”mykv.kv”) MydemoApp(App): def build(self): pass MydemoApp().run() You may also embed the entire “kv” language script as a string into the Python code and load it in the App class with Builder.load_string() method. from kivy.app import App from kivy.lang import Builder kv=””” #kv script goes here “”” MydemoApp(App): def build(self): Builder.load_string(kv) MydemoApp().run() The “kv” language has the following important elements − Rules − A rule in “kv” is similar to a CSS rule. It applies to specific widgets or classes inheriting the specified widget class. A “kv” rule can specify interactive behaviour or use them to add graphical representations of the widgets they apply to. root Widget − You can use the language to create your entire user interface. A “kv” file must contain only one root widget at most. Dynamic Classes − Dynamic classes let you create new widgets and rules on-the-fly, without any Python declaration. A kv script describes the content of a Widget. You can have one root rule, and any number of class or template rules. The root rule is declared by declaring the class of your root widget, without any indentation and followed by the “:” symbol. It sets the root attribute of the App instance. Widget: To declare a class rule, put the name of a widget class between “< >” and followed by the “:” symbol. It defines the appearance and behavior of any instance of that class − <MyWidget>: Kv language rules use indentation for delimitation, same as a Python source code. The thumb rule to remember is that with the angular brackets it”s a rule and without them, it”s a root widget. A schematic example − <MyClass>: prop1: value1 prop2: value2 canvas: CanvasInstruction1: canvasprop1: value1 CanvasInstruction2: canvasprop2: value2 AnotherClass: prop3: value1 There are three keywords specific to the “kv” language − self − always refer to the current widget. Button: text: ”My state is %s” % self.state root − refers to the base widget in the current rule and represents the root widget of the rule (the first instance of the rule) − <MyWidget>: custom: ”Hello world” Button: text: root.custom app − always refers to the instance of your application. Label: text: app.name The Kivy app window can contain only one widget as its root object. However, if you need to compose the app interface with more than one controls, you have to use the layout widget, and place multiple UX widgets in it and then put the layout as the root widget on the app window. The following “kv” file script defines a grid layout which can then be used with the App class − GridLayout: cols:1 Label: text:”Hello” font_size:100 color:(1,0,0,1) Button: text=”Ok” font_size:100 In the above case, the Label widget and a Button are placed in a one-column GridLayout. However, the objects and their properties cannot be accessed from within the Python code. To be able to do so, define the id property in the “kv” script. GridLayout: cols:1 Label: id:l1 text:”Hello” font_size:60 color:(1,0,0,1) Button: id:b1 text=”Ok” font_size:60 When this layout is loaded into the build() method, the App class can access the widget properties through this id. IT has a ids property which is a dictionary with id:value key-value pairs. print (self.ids.l1.text) Let us start with the kv script as follows, consisting of a label and a button in grid layout.

Kivy – Drawing App

Kivy – Drawing App ”; Previous Next In this chapter, we shall learn to develop a simple Kivy app that lets the user draw filled rectangles and circles (ellipses) of different dimensions and colors by dragging the mouse button. The user drags the mouse pointer from the top-left corner to the bottomdown corner of the intended rectangle/ellipse. The approach used in the development of the following code is to capture the mouse coordinates at the touch_down event and touch_up event. Hence we start the program with this code in the build() method of App class − def build(self): self.w= Widget() self.w.bind(on_touch_down=self.on_touch_down) self.w.bind(on_touch_up=self.on_touch_up) return(self.w) We want to let the user choose to draw a rectangle or a circle. Three toggle buttons for choosing to draw either, or clear the canvas have to be added. Hence, we change the layout of App window to box layout, adding the Widget object on top, and three buttons placed below it. lo = BoxLayout(orientation=”vertical”) self.w = Widget() self.w.bind(on_touch_down=self.on_touch_down) self.w.bind(on_touch_up=self.on_touch_up) lo.add_widget(self.w) hlo = BoxLayout(orientation=”horizontal”, size_hint=(1, .1)) self.b2 = ToggleButton(text=”Circle”, group=”mode”) self.b1 = ToggleButton(text=”Rectangle”, state=”down”, group=”mode”) self.b3 = ToggleButton(text=”Clear”, group=”mode”) hlo.add_widget(self.b1) hlo.add_widget(self.b2) hlo.add_widget(self.b3) lo.add_widget(hlo) return lo To draw the desired shape, we need to capture the mouse positions on touch down, and touch up. The on_touch_down() method is simple − def on_touch_down(self, *args): self.td = args[1].pos All the processing happens in on_touch_up() method. The captured coordinates of down event and up event are used to calculate the dimensionsof rectangle or circle. For circle, the x-radius, y-radius and the center are computed as follows − self.tu=args[1].pos xr = (self.tu[0]-self.td[0])/2 yr = (self.td[1]-self.tu[1])/2 c=(self.td[0]+xr, self.td[1]-yr) We need the width and height as well as the top-left corner coordinates for drawing rectangle. The self.td tuple gives top-left point, xr*2 gives the width and yr*2 gives the height. The shapes are drawn on the widget canvas. We choose a random color for drawing. The text property of the pressed button gives us the shape to be drawn − color = (random(), random(), random()) with self.w.canvas: Color(*color) if self.btn==”Rectangle”: Rectangle(pos=self.td, size=(xr*2,yr*2)) if self.btn==”Circle”: Ellipse(pos=(c), size=(xr,yr)) Three toggle buttons are bound to a method. If the caption is Clear, the widget canvas is cleared. def clear_canvas(self, instance, value): self.btn = instance.text self.press = True if value == ”down” and self.btn == ”Clear”: self.w.canvas.clear() return True Example The complete code for the app is given below − from random import random from kivy.app import App from kivy.uix.widget import Widget from kivy.graphics import Color, Ellipse, Line, Rectangle from kivy.uix.togglebutton import ToggleButton from kivy.uix.boxlayout import BoxLayout from kivy.core.window import Window Window.size = (720, 400) class MyPaintApp(App): def clear_canvas(self, instance, value): self.btn = instance.text self.press = True if value == ”down” and self.btn == ”Clear”: self.w.canvas.clear() return True def on_touch_down(self, *args): self.td = args[1].pos def on_touch_up(self, *args): if self.press == True: self.press = False return True self.tu = args[1].pos xr = (self.tu[0] – self.td[0]) / 2 yr = (self.td[1] – self.tu[1]) / 2 c = (self.td[0] + xr, self.td[1] – yr) color = (random(), random(), random()) with self.w.canvas: Color(*color) if self.btn == ”Rectangle”: Rectangle(pos=self.td, size=(xr * 2, yr * 2)) if self.btn == ”Circle”: Ellipse(pos=(c), size=(xr, yr)) def build(self): self.press = False self.btn = ”Rectangle” lo = BoxLayout(orientation=”vertical”) self.w = Widget() self.w.bind(on_touch_down=self.on_touch_down) self.w.bind(on_touch_up=self.on_touch_up) lo.add_widget(self.w) hlo = BoxLayout(orientation=”horizontal”, size_hint=(1, .1)) self.b2 = ToggleButton(text=”Circle”, group=”mode”) self.b1 = ToggleButton(text=”Rectangle”, state=”down”, group=”mode”) self.b3 = ToggleButton(text=”Clear”, group=”mode”) self.b1.bind(state=self.clear_canvas) self.b2.bind(state=self.clear_canvas) self.b3.bind(state=self.clear_canvas) hlo.add_widget(self.b1) hlo.add_widget(self.b2) hlo.add_widget(self.b3) lo.add_widget(hlo) return lo MyPaintApp().run() Output Run the above code. Choose the shape you want to draw. Drag the mouse from top-left to bottom-right. The rectangles/circles are drawn at drawn at different positions with random colors. Click the Clear button to clear the drawings on the canvas. Print Page Previous Next Advertisements ”;

Kivy – Data Loader

Kivy – Data Loader ”; Previous Next A Loader class in Kivy framework is an asynchronous data loader that makes it possible to load an image even if its data is not yet available. This feature is of particular use when you want to load image from an internet URL. The Loader class is defined in kivy.loader module. Typical use of Loader class is like this − from kivy.loader import Loader image = Loader.image(”http://mysite.com/test.png”) Use the loading_image property to specify a default image. Loader.loading_image = Image(default.png”) The Loader class is equipped with the following properties − error_image − Image used for error. For example − Loader.error_image = ”error.png” image(filename) − Load a image using the Loader. A ProxyImage is returned with a loading image. loading_image − Image used for loading. For example − Loader.loading_image = ”loading.png” max_upload_per_frame − The number of images to upload per frame. By default, we”ll upload only 2 images to the GPU per frame. num_workers − Number of workers to use while loading. This setting impacts the loader only on initialization. Once the loader is started, the setting has no impact. from kivy.loader import Loader Loader.num_workers = 4 The default value is “2” for giving a smooth user experience. ProxyImage() − Image returned by the Loader.image() function. proxyImage = Loader.image(“test.jpg”) pause() − Pause the loader. resume() − Resume the loader, after a pause(). run() − Main loop for the loader. start() − Start the loader thread/process. stop() − Stop the loader thread/process. The “on_load” event is fired when the image is loaded or changed. Similarly, the “on_error” is fired when the image cannot be loaded. “error: Exception data that occurred”. Example In the code given below, the Loader object loads an image from an internet URL. The ProxyImage object returned by the Loader binds to a method on its on_load event. The callback method uses its texture as the texture property of the Image object. from kivy.app import App from kivy.uix.image import Image from kivy.loader import Loader from kivy.core.window import Window Window.size = (720,400) class MyApp(App): title=”Loader” def _image_loaded(self, proxyImage): if proxyImage.image.texture: self.image.texture = proxyImage.image.texture def build(self): proxyImage = Loader.image(”https://source.unsplash.com/user/c_v_r/640×480”) proxyImage.bind(on_load=self._image_loaded) self.image = Image() return self.image MyApp().run() Output On execution, it will produce the following output − Print Page Previous Next Advertisements ”;

Kivy – Button Size

Kivy – Button Size ”; Previous Next It is important that a widget on a Kivy application”s user interface should be of an appropriate size. Just as the position property, the size property of the button (any widget for that matter) is governed by the layout in which it is placed. The button size can be configured by the two properties “size” and “size_hint”. The “kivy.uix.button.Button” class inherits these properties from the Widget class. The “size_hint” property of a button is a tuple of values used by its parent layout to decide the size. It defines the size relative to the layout”s size and not absolute size. For example − btn.size_hint = (w, h) Both the parameters “w” and “h” are specified as floating point numbers in the range 0 to 1. For example, 0.5 represents 50% and 1 represents 100%. # This button has width and height of the parent layout btn.size_hint=(1,1) # Width of this button will be half of the container”s width btn.size_hint=(0.5, 1) # This button will be of width and height 20% of the layout btn.size_hint=(.2,.2) On the other hand, the “size” property assigns the width and height of the button in absolute terms and expressed in units of pixels. btn.size=(200,100) However, for the button to be absolutely sized, you must ask Kivy layout to disregard the size hints. If you don”t want to use a size_hint for either the width or height, set the value to None. In other words, you must set “size_hint=(None, None)” before assigning size in absolute measurements. You can also set the size hints for width or height individually with “size_hint_x” and “size_hint_y” properties. Let us say you want to make a button that is 250px wide and 30% of the parent”s height btn.size_hint_x = None btn.size_hint_y= 0.3 widget.width = 250 These properties can also be set in the Button constructor arguments − btn = Button(text=”Hi there!”, size_hint=(None, 0.3), width=250) Example The following program places various buttons in a FloatLayout of the app window with different combinations of size_hint, size, pos_hint and pos properties − from kivy.app import App from kivy.uix.floatlayout import FloatLayout from kivy.uix.button import Button from kivy.core.window import Window Window.size = (720,400) class DemoApp(App): def build(self): f = FloatLayout() b1 = Button(text=”B1″, size_hint=(None, None)) f.add_widget(b1) b2 = Button(text=”B2″, size_hint=(1, None), height=20) f.add_widget(b2) b3 = Button(text=”B3″, size_hint=(None, None), pos=(0, 100), size=(400, 100)) f.add_widget(b3) b4 = Button(text=”B4”, size_hint=(None,.3), width=50, pos_hint={”x”:.6, ”y”:.2} ) f.add_widget(b4) b5 = Button(text=”B5”, size_hint=(None,.9), width=50, pos_hint={”x”:.5, ”y”:.5} ) f.add_widget(b5) return f if __name__ == ”__main__”: DemoApp().run() Output On running this code, you will get the following output window − Print Page Previous Next Advertisements ”;

Kivy – Button Colors

Kivy – Button Colors ”; Previous Next In any GUI application, button is an important component. Its primary function to respond to click event and invoke a callback. To design attractive GUI, the button color should be chosen appropriately. You can configure a button by specifying the color for its caption, background color in normal as well as disabled state. In Kivy, the Button class defines the following color-related properties − color background_color disabled_color outline_color disabled_outline_color color Property The Button class inherits this property from Label class, as Button is a Label that responds to click related events. The color property defines the color of the button text, or the button caption. Since color is of ColorProperty type, it must be specified in (r,g,b,a) format. The colors take the value between “0” to “1”. The “a” component is for transparency. For a button, color defaults to [1, 1, 1, 1]. background_color Property This acts as a multiplier to the texture colour. The default texture is grey, so just setting the background color will give a darker result. The background color of the button is a ColorProperty in the format (r, g, b, a) with default value [1,1,1,1]. disabled_color Property This property is inherited from the Label class. It defines the color of the button text or caption when it is disabled. It”s a ColorProperty and defaults to [1,1,1,3] outline_color Property Inherited from the Label class, this property configures the color of text outline. Note that this requires SDL2 text provider. This property is of ColorProperty type and its default value is [0,0,0,1] disabled_outline_color Property This property defines the color of the text outline when the widget is disabled, in the (r, g, b) format. It is inherited from Label class. This feature requires the SDL2 text provider. The disabled_outline_color is a ColorProperty and defaults to [0, 0, 0]. Example 1 Let us demonstrate the use of color and disabled_color properties. In the following example, we have placed two buttons in a floatlayout. They are instantiated with different color and disabled_color properties. When clicked, the text color changes. from kivy.app import App from kivy.uix.button import Button from kivy.config import Config from kivy.uix.floatlayout import FloatLayout # Configuration Config.set(”graphics”, ”width”, ”720”) Config.set(”graphics”, ”height”, ”300”) Config.set(”graphics”, ”resizable”, ”1”) class HelloApp(App): def on_button_press(self, instance): instance.disabled = True def build(self): flo = FloatLayout() btn1 = Button(text= ”Hello Python”, color= [1,0,0,1], disabled_color = [0,0,1,1], font_size= 40, size_hint= (.4, .25), pos_hint= {”center_x”:.5, ”center_y”:.8}) btn1.bind(on_press = self.on_button_press) btn2 = Button(text= ”Hello Kivy”, color= [0,0,1,1], disabled_color = [1,0,0,1], font_size= 40, size_hint= (.4, .25), pos_hint= {”center_x”:.5, ”center_y”:.2}) flo.add_widget(btn1) btn2.bind(on_press = self.on_button_press) flo.add_widget(btn2) return flo if __name__ == ”__main__”: HelloApp().run() Output Initially, both the buttons are enabled. When you press the buttons, they get disabled (they are unable to receive the “on_press” event) and the text color changes as per the configuration. Example 2 In the following program, when any button is clicked, its text color and background color is interchanged. from kivy.app import App from kivy.uix.button import Button from kivy.config import Config from kivy.uix.floatlayout import FloatLayout # Configuration Config.set(”graphics”, ”width”, ”720”) Config.set(”graphics”, ”height”, ”300”) Config.set(”graphics”, ”resizable”, ”1”) class HelloApp(App): def on_button_press(self, instance): print(“change color”) instance.background_color, instance.color = instance.color, instance.background_color def build(self): flo = FloatLayout() self.btn1 = Button(text=”Hello Python”, color=[1, 0, 0, 1], background_color=[0, 0, 1, 1], font_size=40, size_hint=(.4, .25), pos_hint={”center_x”: .5, ”center_y”: .8}) self.btn2 = Button(text=”Hello Kivy”, color=[0, 0, 1, 1], background_color=[1, 0, 0, 1], font_size=40, size_hint=(.4, .25), pos_hint={”center_x”: .5, ”center_y”: .2}) flo.add_widget(self.btn1) self.btn1.bind(on_press=self.on_button_press) self.btn2.bind(on_press=self.on_button_press) flo.add_widget(self.btn2) return flo if __name__ == ”__main__”: HelloApp().run() Output When you click any of the two buttons, their colors get interchanged as shown here − Print Page Previous Next Advertisements ”;

Kivy – Factory

Kivy – Factory ”; Previous Next The factory class in Kivy is used to automatically register any class or module and instantiate classes from it anywhere in your project. The Factory class is defined in the “kivy.factory” module. Factory Pattern is a software architecture pattern in object-oriented programming. A factory is an object for creating other objects. It is a function or method that returns objects or class from some method call that returns a “new” object may be referred to as a “factory”, as in factory method or factory function. The “kivy.factory.Factory” class creates instances of classes and adds them to the widget tree. The widget tree controls elements on a user interface. Here is an example of creating a custom button class registered with Factory. from kivy.factory import Factory from kivy.uix.button import Button Factory.register(”MyCustomButton”, cls=Button) btn = MyCustomButton( text: “Click me”) Similarly, you can create a class with Factory − from kivy.factory import Factory from kivy.uix.label import Label class MyLabel(Label): pass Factory.register(”MyLabel”, cls=MyLabel) lbl = MyLabel(text: “Hello world”) By default, the first classname you register via the factory is permanent. If you wish to change the registered class, you need to unregister the classname before you re-assign it. from kivy.factory import Factory Factory.register(”NewWidget”, cls=NewWidget) widget = Factory.NewWidget() Factory.unregister(”NewWidget”) Factory.register(”NewWidget”, cls=CustomWidget) customWidget = Factory.NewWidget() Example The following Kivy application uses Factory to register a MyPopup class which is a Popup widget in Kivy library. The Kivy App class code is as follows − from kivy.app import App from kivy.uix.widget import Widget from kivy.lang import Builder from kivy.core.window import Window Window.size = (720,400) Builder.load_file(”popup.kv”) class MyLayout(Widget): pass class FactorydemoApp(App): def build(self): return MyLayout() FactorydemoApp().run() In order to populate the app window, use the following “kv” script (popup.kv) #:import Factory kivy.factory.Factory <MyPopup@Popup> auto_dismiss: False size_hint: 0.6, 0.4 pos_hint: {“x”:0.2, “top”: 0.9} title: “Popup Box” BoxLayout: orientation: “vertical” size: root.width, root.height Label: text: “Hello Kivy” font_size: 24 Button: text: “Close” font_size: 24 on_release: root.dismiss() <MyLayout> BoxLayout: orientation: “vertical” size: root.width, root.height Label: text: “Factory Example” font_size: 32 Button: text: “Click here” font_size: 32 on_release: Factory.MyPopup().open() As you can see, the MyPopup class is registered in the Factory and its open() method is called when the button is clicked Output Run the program to display the window with the “Click here” button. On clicking it, the popup appears on the application window. Print Page Previous Next Advertisements ”;

Kivy – Image Viewer

Kivy – Image Viewer ”; Previous Next In this chapter, we shall build a simple Image Viewer app in Kivy. The code below uses Kivy”s Image widget and buttons for navigation through the list of images in the selected folder. There is also a button which opens a FileChooser to let the user select different folder to view the images in. First, we need to build a list of all the image files in the currently selected folder. We use the os.listdir() method for this purpose. import os self.idx=0 self.fillist=[] dir_path = ”.” for file in os.listdir(dir_path): if file.endswith(”.png”): self.fillist.append(file) The construction of app interface involves a vertical box layout, in which the Image object is placed on top and another horizontal box layout holding three buttons. lo=BoxLayout(orientation=”vertical”) self.img= Image(source=self.fillist[self.idx]) lo.add_widget(self.img) hlo=BoxLayout(orientation=”horizontal”, size_hint=(1, .1)) self.b1 = Button(text = ”Dir”, on_press=self.onButtonPress) self.b2 = Button(text = ”Prev”, on_press=self.previmg) self.b3 = Button(text = ”Next”, on_press=self.nextimg) hlo.add_widget(self.b1) hlo.add_widget(self.b2) hlo.add_widget(self.b3) lo.add_widget(hlo) The Image widget displays the first available image to start with. When the button captioned “Next” is clicked, the index pointing to the filelist is incremented; and when the “Previous” button is clicked, it is decremented, loading the indexed image file in the Image object. def previmg(self, instance): self.idx-=1 if self.idx<0: self.idx=0 self.img.source=self.fillist[self.idx] def nextimg(self, instance): self.idx+=1 if self.idx>=len(self.fillist): self.idx=len(self.fillist)-1 self.img.source=self.fillist[self.idx] The third button (captioned Dir) pops up a FileChooser dialog. You can choose the required folder to view. def onButtonPress(self, button): layout=GridLayout(cols=1) fw=FileChooserListView(dirselect=True, filters=[“!*.sys”]) fw.bind(on_selection=self.onselect) closeButton = Button( text = “OK”, size_hint=(None, None), size=(100,75) ) layout.add_widget(fw) layout.add_widget(closeButton) self.popup = Popup( title=”Choose Folder”, content=layout, auto_dismiss=False, size_hint=(None, None), size=(400, 400) ) self.popup.open() Example Images in the current folder populate the fillist to start with. Here is the complete code − from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.label import Label from kivy.uix.popup import Popup from kivy.uix.image import Image from kivy.uix.button import Button from kivy.uix.filechooser import FileChooserListView from kivy.core.window import Window Window.size = (720, 400) class ImageViewerApp(App): def previmg(self, instance): self.idx -= 1 if self.idx < 0: self.idx = 0 self.img.source = self.fillist[self.idx] def nextimg(self, instance): self.idx += 1 if self.idx >= len(self.fillist): self.idx = len(self.fillist) – 1 self.img.source = self.fillist[self.idx] def onButtonPress(self, button): layout = GridLayout(cols=1) fw = FileChooserListView(dirselect=True, filters=[“!*.sys”]) fw.bind(on_selection=self.onselect) closeButton = Button( text=”OK”, size_hint=(None, None), size=(100, 75) ) layout.add_widget(fw) layout.add_widget(closeButton) self.popup = Popup( title=”Choose Folder”, content=layout, auto_dismiss=False, size_hint=(None, None), size=(400, 400) ) self.popup.open() closeButton.bind(on_press=self.on_close) def onselect(self, *args): print(args[1][0]) def on_close(self, event): self.popup.dismiss() def build(self): import os self.idx = 0 self.fillist = [] dir_path = ”.” for file in os.listdir(dir_path): if file.endswith(”.png”): self.fillist.append(file) lo = BoxLayout(orientation=”vertical”) self.img = Image(source=self.fillist[self.idx]) lo.add_widget(self.img) hlo = BoxLayout(orientation=”horizontal”, size_hint=(1, .1)) self.b1 = Button(text=”Dir”, on_press=self.onButtonPress) self.b2 = Button(text=”Prev”, on_press=self.previmg) self.b3 = Button(text=”Next”, on_press=self.nextimg) hlo.add_widget(self.b1) hlo.add_widget(self.b2) hlo.add_widget(self.b3) lo.add_widget(hlo) return lo ImageViewerApp().run() Output When you run this code, it will display the image at index “0” − Click the navigation buttons to go forward and back. Click the “Dir” button to select a new folder. Print Page Previous Next Advertisements ”;

Kivy – Buttons

Kivy – Buttons ”; Previous Next A button is one of the most important elements in any GUI library, including Kivy. A button object consists of a label, usually to indicate its purpose (such as one with Start caption, or one with a “folder” icon to indicate “open file action”), and having the ability to respond to certain events such as touch or mouse click. The Button class is defined in the “kivy.uix.button” module. The appearance of a Button object can be configured by the same set of properties that are defined in the Label class. The Button class also inherits from the ButtonBehavior mixin. The Button object is instantiated with the following syntax − b1 = Button(**kwargs) To configure a button, you can specify its properties as keyword arguments to the constructor − background_color − The background color of the button is a ColorProperty in the format (r, g, b, a) with default value [1,1,1,1]. background_disabled_down − The background image of the button is a StringProperty, a string containing path to an image file and is used for the default graphical representation when the button is disabled and pressed. background_disabled_normal − Background image of the button is also an image path, used for the default graphical representation when the button is disabled and not pressed. background_down − Background image of the button used as the default graphical representation when the button is pressed. background_normal − Background image of the button used as the default graphical representation when the button is not pressed. In addition to the above, the Button also inherits properties from Label class, some of them as follows − bold − Indicates use of the bold version of your font. It is a BooleanProperty and defaults to False. underline − Adds an underline to the text. This feature requires the SDL2 text provider, it is a BooleanProperty and defaults to False. strikethrough − Adds a strikethrough line to the text. This feature requires the SDL2 text provider. It is a BooleanProperty and defaults to False. text − Text of the label. For example − widget = Button(text=”Hello world”) text is a StringProperty and defaults to ””. color − Text color, in the format (r, g, b, a). It is a ColorProperty ,defaults to [1, 1, 1, 1]. font_size − Font size of the text, in pixels. “font_size” is a NumericProperty and defaults to 15sp. Button class also inherits state property from ButtonBehavior class. state − The state of the button, must be one of ”normal” or ”down”. The state is ”down” only when the button is currently touched/clicked, otherwise its ”normal”. It is an OptionProperty and defaults to ”normal”. Button class also inherits properties such as disabled, height, width and pos, etc., from the Widget class. If you want to display a Button on a Kivy application window, then you can do it by declaring a Button object in build() method, or use the “kv” language script. Displaying a Button Using the build() Method Let us configure the Button with some of the properties explained above − Example from kivy.app import App from kivy.uix.button import Button from kivy.config import Config # Configuration Config.set(”graphics”, ”width”, ”720”) Config.set(”graphics”, ”height”, ”300”) Config.set(”graphics”, ”resizable”, ”1”) class HelloApp(App): def build(self): b1 = Button(text = “A Kivy Button”, font_size=50, color = [0.8, 0.2, 0.3, 1]) return b1 app = HelloApp() app.run() Output Run this code and you will get the following output − Displaying a Button Using the “kv” Language Method Example Save the following script as “hello.kv”. Button: text: ”A Kivy Button” font_size: ”20pt” underline: True background_color: [1,0,0,1] size_hint: (.25, .25) pos_hint: {”center_x”:.5, ”center_y”:.5} Output Comment out the build() method in the App class and run the application again. You will get the following window as the output − Print Page Previous Next Advertisements ”;

Kivy – Slider

Kivy – Slider ”; Previous Next In the Kivy framework, the Slider widget is an extremely useful control when you want to set value of a continuously variable numeric property. For example, the brightness of TV screen or mobile device or speaker sound. The appearance of the slider widget is a horizontal or vertical bar with a knob sliding over it to set the value. When the knob is to the left of a horizontal slider, it corresponds to a minimum value; and when it is to the extreme right, it corresponds to the maximum. The Slider class is defined in the “kivy.uix.slider” class. from kivy.uix.slider import Slider slider = Slider(**kwargs) To create a basic slider control in Kivy, we can use the following code − from kivy.uix.slider import Slider s = Slider(min=0, max=100, value=25) The default orientation of the slider control is horizontal. Set orientation=”vertical” if needed. You should get a slider as shown below on the Kivy application window. The knob can be moved along the slider with a mouse or touch (in case of a touchscreen). To invoke a certain action on the basis of change in slider value, bind the value property to a certain callback. def on_value_changed(self, instance, val): print (val) s.bind(value = on_value_changed) Here are some of the important properties of the Slider class − max − Maximum value allowed for value. max is a NumericProperty and defaults to 100. min − Minimum value allowed for value. min is a NumericProperty and defaults to 0. orientation − Orientation of the slider. orientation is an OptionProperty and defaults to ”horizontal”. Can take a value of ”vertical” or ”horizontal”. padding − Padding of the slider. The padding is used for graphical representation and interaction. It prevents the cursor from going out of the bounds of the slider bounding box. padding is a NumericProperty and defaults to 16sp. range − Range of the slider in the format (minimum value, maximum value) is a ReferenceListProperty of (min, max) properties. sensitivity − Whether the touch collides with the whole body of the widget or with the slider handle part only. sensitivity is a OptionProperty and defaults to ”all”. Can take a value of ”all” or ”handle”. step − Step size of the slider. Determines the size of each interval or step the slider takes between min and max. step is a NumericProperty and defaults to 0. value − Current value used for the slider. value is a NumericProperty and defaults to 0. value_track − Decides if slider should draw the line indicating the space between min and value properties values. It is a BooleanProperty and defaults to False. value_track_color − Color of the value_line in rgba format. value_track_color is a ColorProperty and defaults to [1, 1, 1, 1]. value_track_width − Width of the track line, defaults to 3dp. Example In the code below, we use three slider widgets to let the user set RGB value for the desired color. The values of the sliders are used to Change the RGB values. For example, the RED slider change sets the value of ”r” component − def on_red(self, instance, val): self.r = int(val)/255 self.colour=[self.r, self.g, self.b, self.t] self.redValue.text = str(int(val)) Similar callbacks for Green and Blue are also coded. These are assigned the value of colur variable which is of ColorProperty type. It is bound to the color property of a Label widget. colour = ColorProperty([1,0,0,1]) def on_colour_change(self, instance, value): self.ttl.color=self.colour As a result, setting RGB values by the sliders changes the text color of the Label. Three slider controls along with the required labels are placed in an inner grid layout with four columns. An upper grid with one column houses a label, whose color is sought to be changed with the slider movement. The complete code is given below − from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.uix.slider import Slider from kivy.uix.label import Label from kivy.properties import ColorProperty, NumericProperty from kivy.core.window import Window Window.size = (720, 400) class SliderExample(App): r = NumericProperty(0) g = NumericProperty(0) b = NumericProperty(0) t = NumericProperty(1) colour = ColorProperty([1, 0, 0, 1]) def on_colour_change(self, instance, value): self.ttl.color = self.colour def on_red(self, instance, val): self.r = int(val) / 255 self.colour = [self.r, self.g, self.b, self.t] self.redValue.text = str(int(val)) def on_green(self, instance, val): self.g = int(val) / 255 self.colour = [self.r, self.g, self.b, self.t] self.greenValue.text = str(int(val)) def on_blue(self, instance, val): self.b = int(val) / 255 self.colour = [self.r, self.g, self.b, self.t] self.blueValue.text = str(int(val)) def build(self): maingrid = GridLayout(cols=1) self.ttl = Label( text=”Slider Example”, color=self.colour, font_size=32 ) maingrid.add_widget(self.ttl) grid = GridLayout(cols=4) self.red = Slider(min=0, max=255) self.green = Slider(min=0, max=255) self.blue = Slider(min=0, max=255) grid.add_widget(Label(text=”RED”)) grid.add_widget(self.red) grid.add_widget(Label(text=”Slider Value”)) self.redValue = Label(text=”0”) grid.add_widget(self.redValue) self.red.bind(value=self.on_red) grid.add_widget(Label(text=”GREEN”)) grid.add_widget(self.green) grid.add_widget(Label(text=”Slider Value”)) self.greenValue = Label(text=”0”) grid.add_widget(self.greenValue) self.green.bind(value=self.on_green) grid.add_widget(Label(text=”BLUE”)) grid.add_widget(self.blue) grid.add_widget(Label(text=”Slider Value”)) self.blueValue = Label(text=”0”) grid.add_widget(self.blueValue) self.blue.bind(value=self.on_blue) self.bind(colour=self.on_colour_change) maingrid.add_widget(grid) return maingrid root = SliderExample() root.run() Output When you run this code, it will produce an output window like the one shown here − Print Page Previous Next Advertisements ”;

Kivy – Vector

Kivy – Vector ”; Previous Next In Euclidean geometry, a vector is an object that represents a physical quantity that has both the magnitude and direction. Kivy library includes Vector class and provides functionality to perform 2D vector operations. The Vector class is defined in kivy.vector module. Kivy”s Vector class inherits Python”s builtin list class. A Vector object is instantiated by passing x and y coordinate values in a cartesian coordinate system. from kivy.vector import Vector v=vector(10,10) The two parameters are accessible either by the subscript operator. First parameter is v[0], and second parameter is v[1]. print (v[0], v[1]) They are also identified as x and y properties of a Vector object. print (v.x, v.y) You can also initialize a vector by passing a two value list or a tuple to the constructor. vals = [10,10] v = Vector(vals) Example The Vector class in Kivy supports vector operations represented by the usual arithmetic operations +, −, / The addition of two vectors (a,b)+(c,d) results in a vector (a+c, b+d). Similarly, “(a,b) – (c,d)” is equal to “(a − c, b − d)”. from kivy.vector import Vector a = (10, 10) b = (87, 34) print (“addition:”,Vector(1, 1) + Vector(9, 5)) print (“Subtraction:”,Vector(9, 5) – Vector(5, 5)) print (“Division:”,Vector(10, 10) / Vector(2., 4.)) print (“division:”,Vector(10, 10) / 5.) Output addition: [10, 6] Subtraction: [4, 0] Division: [5.0, 2.5] division: [2.0, 2.0] Methods in Vector Class Following methods are defined in Kivy”s Vector class − angle() It computes the angle between a vector and an argument vector, and returns the angle in degrees. Mathematically, the angle between vectors is calculated by the formula − $$theta =cos^{-1}left [ frac{xcdot y}{left| xright|left|y right|} right ]$$ The Kivy code to find angle is − Example a=Vector(100, 0) b=(0, 100) print (“angle:”,a.angle(b)) Output angle: -90.0 distance() It returns the distance between two points. The Euclidean distance between two vectors is computed by the formula − $$dleft ( p,q right )=sqrt{left ( q_{1}-p_{1} right )^{2}+left ( q_{2}-p_{2} right )^{2}}$$ The distance() method is easier to use. Example a = Vector(90, 33) b = Vector(76, 34) print (“Distance:”,a.distance(b)) Output Distance: 14.035668847618199 distance2() It returns the distance between two points squared. The squared distance between two vectors x = [ x1, x2 ] and y = [ y1, y2 ] is the sum of squared differences in their coordinates. Example a = (10, 10) b = (5,10) print (“Squared distance:”,Vector(a).distance2(b)) Output Squared distance: 25 dot(a) Computes the dot product of “a” and “b”. The dot product (also called the scalar product) is the magnitude of vector b multiplied by the size of the projection of “a” onto “b”. The size of the projection is $costheta $(where $theta$ is the angle between the 2 vectors). Example print (“dot product:”,Vector(2, 4).dot((2, 2))) Output dot product: 12 length() It returns the length of a vector. length2() method Returns the length of a vector squared. Example pos = (10, 10) print (“length:”,Vector(pos).length()) print (“length2:”,Vector(pos).length2()) Output length: 14.142135623730951 length2: 200 rotate(angle) Rotate the vector with an angle in degrees. Example v = Vector(100, 0) print (“rotate:”,v.rotate(45)) Output rotate: [70.71067811865476, 70.71067811865476] Print Page Previous Next Advertisements ”;