Kivy – Widgets

Kivy – Widgets ”; Previous Next The user interface of a Kivy app is designed with various widgets in Kivy library. The “kivy.uix” module includes definitions of classes corresponding to the widget names. These classes provide the properties and functionality of the corresponding widget object. The various widgets in Kivy library can be classified under following categories − General Purpose Widgets These widgets are classical in nature in the sense they are used in the interface design of most applications. The UX widgets like Label, various Button types, input box, Image container, slider and progress indicator etc. belong to this category. Some of the UX widgets are shown below − Layouts 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. It may be noted that the layout widgets do not have a visual representation of their own. Kivy provides various layouts such as grid layout, box layout, float layout etc. Complex UX Widgets The widgets of this type are the the result of combining multiple classic widgets. They are complex because their assembly and usage are not as generic as the classical widgets. Examples in the category of complex widgets are Drop-Down List, FileChooser, Spinner, Video player, VKeyboard etc. Behaviors Widgets These widgets do not have their own rendering but respond to the graphics instructions or interaction (touch) behavior of their children. Scatter, Stencil View widgets are of this type. Screen Manager Manages screens and transitions when switching from one to another. Widget Class The Widget class, defined in kivy.uix.widget module is the base for all the widget classes. The common properties such as size, width, height, pos, pos_hint, etc. defined in this Widget class are inherited by other widgets. The interactivity of any Widget object depends on two aspects: the “event handlers” and the “property callbacks”. If a widget is bound to a certain handler in the occurrence of an event of certain type, the corresponding handler function is invoked. def callback(instance): print(”Callback handler”) wid = Widget() wid.bind(on_event=callback) A callback function is also invoked on the basis of a certain property. If a property changes, the widget can respond to the change in the ”on_<propname>” callback. def on_pos_change(instance, value): print(”The widget position changed to ”, value) wid = Widget() wid.bind(pos=on_pos_change) Neither the base Widget class nor any of the Widgets have a draw() method. Every widget has its own Canvas that you can use to draw. widget = Widget() with widget.canvas: Rectangle(pos=widget.pos, size=widget.size) The graphic instruction such as Color, Rectangle and Line, Scale and Rotate can be added to the Canvas of any widget. In Kivy, events are propagated upwards from the first child through the other children. If a widget has children, the event is passed through its children before being passed on to the widget after it. Each widget is added to its parent by the add_widget() method. Each addition is identified by an incrementing index. box = BoxLayout() l1=Label(text=”a”) l1=Label(text=”b”) l1=Label(text=”c”) box.add_widget(l1) box.add_widget(l2) box.add_widget(l3) The indices at which the labels are added are 0,1 and 2 for l1, l2, l3 respectively. You can explicitly give the index argument to the add_widget() method. box.add_widget(l1, index=1) box.add_widget(l2, index=0) box.add_widget(l3, index=2) In case the widget arrangement is nested, the event on the innermost widget is propagated upwards. Suppose that a Button is a child widget, added to the Widget object itself. Hence, the touch_down callback will be invoked for both the objects. To confirm that the touch event has occurred on the button only, use collide_points() method. def callback(self, touch): if instance.collide_point(touch.x, touch.y): #consume event return True else: #the upper level widget processes the event Example A basic Kivy app shows a simple one line message on a label added to a Widget object with the code below − from kivy.app import App from kivy.uix.label import Label from kivy.uix.widget import Widget from kivy.core.window import Window Window.size = (720,300) class HelloApp(App): def build(self): w = Widget() l1=Label( text=”Fortune Favours the Brave!”, font_size=50, size=(200,100), pos_hint={”center_x”:.5, ”center_y”:.5}, pos=(250,200) ) w.add_widget(l1) return w app = HelloApp() app.run() Output When you run this code, it will produce the following output window − Print Page Previous Next Advertisements ”;

Kivy – Camera

Kivy – Camera ”; Previous Next With the Camera widget in Kivy, it is possible to display the video stream from a camera device. Kivy may take some time to initialize the camera device, and update the widget texture afterwards. The Camera class is defined in the “kivy.uix.camera: module. from kivy.uix.camera import Camera cam = Camera(**kwargs) If the system finds multiple camera devices, you need to specify the camera to be used by its index. cam = Camera(index=1) You can also specify the camera resolution with the resolution argument − cam = Camera(index=1, resolution=(640, 480)) The kivy.uix.camera.Camera class is a concrete implementation of the core Camera class from the “kivy.core.camera” module, and performs the initialization and frame capture functions. Kivy needs to find an appropriate camera provider to be able to detect the hardware. For this purpose, install the latest version of opencv-python package, which also installs its dependency packages including NumPy. pip install opencv-python To start streaming the feed from your camera on the app window, set the play property of the Camera object to True, and set it to False to stop the feed. cam.play = True To capture the snapshot of the camera stream to an image, use the export_to_png() method. Specify the filename to save to. The Camera class defines following attributes − index − Index of the used camera, starting from 0. Setting it to -1 to allow auto selection. play − Boolean indicating whether the camera is playing or not. You can start/stop the camera by setting this property − # create the camera, and start later (default) cam = Camera() # and later cam.play = True # to sop cam.play = False resolution − Preferred resolution to use when invoking the camera. If you are using [-1, -1], the resolution will be the default one. To set the desired resolution, provided it is supported by the device − cam = Camera(resolution=(640, 480)) Example The following example code adds a Camera widget and a ToggleButton inside a vertical BoxLayout. The callback bound to the toggle button sets the camera object”s play property to True when the button is down, and otherwise the video is stopped. from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.togglebutton import ToggleButton from kivy.uix.camera import Camera from kivy.core.window import Window Window.size = (720,350) class TestCameraApp(App): def build(self): box=BoxLayout(orientation=”vertical”) self.mycam=Camera(play=False, resolution= (640, 480)) box.add_widget(self.mycam) tb=ToggleButton(text=”Play”, size_hint_y= None, height= ”48dp”) tb.bind(on_press=self.play) box.add_widget(tb) return box def play(self, instance): if instance.state==”down”: self.mycam.play=True instance.text=”Stop” else: self.mycam.play=False instance.text=”Play” TestCameraApp().run() Output Run the code and check the output − You can also use the “kv” language script to design the application window layout. Save the following script as “TestCamera.kv”, comment out the code in the build() method, and just place a “pass” statement in it. BoxLayout: orientation: ”vertical” Camera: id: camera resolution: (640, 480) play: False ToggleButton: text: ”Play” on_press: camera.play = not camera.play size_hint_y: None height: ”48dp” Print Page Previous Next Advertisements ”;

Kivy – Images

Kivy – Images ”; Previous Next Being able to display images is an essential requirement of any GUI application. Kivy framework includes Image widget as an image container. It is capable of loading the image data from png, jpg and GIF files. For SVG files, you may have to another widget named as Svg itself. Kivy contains two image widgets − Image and AsyncImage. They are defined in the “kivy.uix.image” module. The Image widget is used to load an image file available in the local machine. from kivy.uix.image import Image img = Image(source = ”logo.png”) To load any image from any external source, you need to use the AsyncImage widget. AsyncImage class is a subclass of the Image class. from kivy.uix.image import AsyncImage img = AsyncImage(source = ”http://xyz.com/logo.png”) If you need to display images by retrieving them from URL”s, AsyncImage does it in a background thread without blocking your application. The Image class defines following properties − source − Filename / source of your image. source is a StringProperty and defaults to None. fit_mode − If the size of the image is different than the size of the widget, this property determines how the image should be resized to fit inside the widget box. Available Options scale-down − For an image bigger than the Image widget dimensions, the image will be scaled down to fit inside the widget box, maintaining its aspect ratio and without stretching. If the size of the image is smaller than the widget, it will be displayed at its original size. fill − the image is stretched to fill the widget regardless of its aspect ratio or dimensions. This option can lead to distortion of the image, if the image has a different aspect ratio than the widget. contain − the image is resized to fit inside the widget box, maintaining its aspect ratio. If the image size is larger than the widget size, the behavior will be similar to “scale-down”. However, if the size of the image size is smaller than the widget size, unlike “scale-down, the image will be resized to fit inside the widget. cover − the image will be stretched horizontally or vertically to fill the widget box, maintaining its aspect ratio. If the image has a different aspect ratio than the widget, then the image will be clipped to fit. texture − Texture object of the image. The texture represents the original, loaded image texture. It is stretched and positioned during rendering according to the fit_mode property. texture_size − Texture size of the image. This represents the original, loaded image texture size. color − Image color, in the format (r, g, b, a). This attribute can be used to ”tint” an image. However, if the source image is not gray/white, the color will not really work as expected. image_ratio − A read-only property that returns Ratio of the image (width / float(height). reload() − Reload image from disk. This facilitates re-loading of images from disk in case the image content changes. img = Image(source = ”1.jpg”) img.reload() Example In the following example code, we mainly try to demonstrate the effect of fit_mode property. Given below is a “kv” language script that displays different images in carousel widget. Each image has a different value of fit_mode property. The “kv” language script is − Carousel: direction:”top” Image: source:”1.png” fit_mode:”scale-down” Image: source:”TPlogo.png” fit_mode:”contain” Image: source:”TPlogo.png” fit_mode:”fill” Image: source:”TPlogo.png” fit_mode:”cover” Output After loading this script in a Kivy App class and running it, different images will be displayed as per the respective fit_mode − fit_mode = scaled-down The source is bigger than the Image widget. fit_mode=contain Source image smaller than the Image widget. fit_mode: fill Image is resized to fit without losing aspect ratio. fill_mode=cover Image is stretched to cover the entire widget area. Print Page Previous Next Advertisements ”;

Kivy – Line

Kivy – Line ”; Previous Next In the Kivy library, “Line” is an important vertex instruction in the “kivy.graphics” module. In Kivy, all the drawings are done on the Canvas associated with any of the available widgets. The Line instruction draws a line, or a sequence of lines as well as other shapes like rectangle, ellipse, Bezier, etc. It must be noted that the Kivy drawing instructions are not automatically relative to the position or size of the widget. On the contrary, the canvases of all the widgets share a common coordinate space. The Line function requires a list of numeric values. The interpretation of the numbers depends on the parameter to which this list is assigned. The parameters of List function are points, rectangle, ellipse, Bezier, etc. Draw a Rectangle Syntax You can draw a rectangle with Line function with the following syntax − with self.canvas: Line(rectangle=[x, y, w, h], width) Here, “x” and “y” represent the bottom-left position of the rectangle, and “w” and “h” represent the width and height. The line is automatically closed. You can also use a rounded_rectangle property to build a rectangle with round corners. The argument must be a tuple of one of the following forms − (x, y, width, height, corner_radius) (x, y, width, height, corner_radius, resolution) (x, y, width, height, corner_radius1, corner_radius2, corner_radius3, corner_radius4) (x, y, width, height, corner_radius1, corner_radius2, corner_radius3, corner_radius4, resolution) Example from kivy.app import App from kivy.uix.widget import Widget from kivy.graphics import * from kivy.core.window import Window Window.size = (720,300) class drawRectangle(App): def build(self): widget = Widget() with widget.canvas: Color(1, 0, 1, 1) Line( rectangle=(50, 50, 300, 200), width=3 ) Line(rounded_rectangle=(500, 200, 300, 200, 20, 20, 20, 20)) return widget drawRectangle().run() Output It will produce the following output window − Draw an Ellipse You need to assign a list of numeric values to the ellipse property of the Line instruction. The value of ellipse argument must be a tuple of (x, y, width, height, angle_start, angle_end, segments) Where, “x” and “y” represent the bottom left of the ellipse “width” and “height” represent the size of the ellipse. If both these values are same, the result will be a circle “angle_start” and “angle_end” are in degree. The default value is 0 and 360. “segments” is the precision of the ellipse. You can use this property to create polygons with 3 or more sides. Values smaller than 3 will not be represented. Example In the code below, Line instruction is used to draw ellipse with different arguments − from kivy.app import App from kivy.uix.widget import Widget from kivy.graphics import * from kivy.core.window import Window Window.size = (720,400) class drawEllipse(App): def build(self): widget = Widget() with widget.canvas: Color(0.5, .2, 0.4, 1) Line(ellipse=(500, 70, 200, 200), width=4) Line(ellipse=(100, 200, 100, 200), width=4) Color(.2, .8, 0, 1) Line(ellipse=(200, 100, 200, 100), width=4) Line(ellipse=(500, 300, 250, 90, 45, 270), width=3) Color(.1, .8, .3, 1) Line(ellipse=(200, 400, 200, 80, 180, 420, 30), width=5) return widget drawEllipse().run() Output Draw Bezier Curve A Bezier curve is weighted by some control points, that we include within the instruction. The Line() function accepts Bezier parameter to which a list of pairs of (x,y) coordinates are passed. The argument must be a list of 2n elements, “n” being the number of points. with self.canvas: Line(bezier=[x1, y1, x2, y2, x5, y3], width) It may be noted that the points parameter of Line instruction function also receives a similar set of 2n elements. The points property draws a line between successive points. with self.canvas: Line(points=[x1, y1, x2, y2, x5, y3], width) The point parameter to Line instruction only draws the points corresponding to each x-y coordinate pair, without any line connecting them. with self.canvas: Line(point=[x1, y1, x2, y2, x5, y3], width) Example The following code uses the same set of “x” and coordinate pairs to draw only the points, line, and a Bezier line − from kivy.app import App from kivy.uix.widget import Widget from kivy.graphics import * from kivy.core.window import Window Window.size = (720, 400) class drawBezier(App): def build(self): widget = Widget() with widget.canvas: Color(0, 1, 1, 1) Bezier( points=[700, 400, 450, 300, 300, 350, 350, 200, 200, 100, 150, 10], segments=20 ) Color(1, 1, 0, 1) Point( points=[700, 400, 450, 300, 300, 350, 350, 200, 200, 100, 150, 10], pointsize=5 ) Color(.1, .1, .8) Line( points=[700, 400, 450, 300, 300, 350, 350, 200, 200, 100, 150, 10], pointsize=3 ) return widget drawBezier().run() Output When you run this code, it will produce an output window like the one shown here − It may be noted that Kivy provides another set of vertex instructions to draw these shapes with Rectangle, Ellipse, Bezier instructions. These are different from the rectangle, ellipse and bezier parameters to Line instruction. Note the uppercased first alphabets of instruction itself and parameter (Ellipse instruction vs. ellipse parameter of Line instruction). The Line function draws the shapes without recalculating the points. Print Page Previous Next Advertisements ”;

Kivy – Progress Bar

Kivy – Progress Bar ”; Previous Next When a GUI application is performing some process that is time consuming, there should be some mechanism to let the user know about its progress. The Progressbar widget in Kivy framework shows a visual representation of the progress of an ongoing task. Kivy”s progress bar widget only supports horizontal mode, and appears on the application window with incremental progress. The Progressbar class is defined in the “kivy.uix.progressbar” module. from kivy.uix.progressbar import ProgressBar pb = Progressbar(**kwargs) The Progressbar widget is a display-only widget, and doesn”t have any interactive elements, as is doesn”t raise and propagate any events. To create an instance of Progressbar, you need to set its max property. from kivy.uix.progressbar import ProgressBar pb = ProgressBar(max=1000) The widget has value property. You can assign it to any number less than its “max” property. pb.value=100 However, since the progressbar class doesn”t have any events and event handlers, we need to manually link the value property to some process. It can be done by periodically reading the instantaneous value of an attribute of the progressive task, and update the value property of the progress bar. Let us say we have a long for loop, that takes its next iteration after every one second. for i in range(1000): time.delay(1) print (i) We want to show the increment of I on the progress bar. So, we schedule a clock event that calls a function after every one second. progev = Clock.schedule_interval(update_progress, 1.0) After each second, the update_progesss() function updates the value property of the progress bar to the iteration counter i def update_progress(): pb.value = i Example Let us implement this approach in the following code. The GUI design contains two buttons and a label. When the start button is pressed, it loads a mp3 file into the Sound object. The length of the sound file is used as the max property of the progressbar self.sound = SoundLoader.load(”sample.mp3”) self.length = self.sound.length As the play() method is invoked, we schedule an progress event as shown above. self.prog_ev = Clock.schedule_interval(self.update_progress, 1.0) The update_progress() method reads the pos property of the Sound object and uses it to update the value property of the progressbar def update_progress(self, dt): if self.sound.state==”play”: if self.prg.value < self.length: self.progress += 1 # Update value. self.prg.value=self.progress Here is the complete code − from kivy.app import App from kivy.clock import Clock from kivy.uix.button import Button from kivy.uix.label import Label from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.core.audio import SoundLoader from kivy.uix.progressbar import ProgressBar from kivy.properties import NumericProperty from kivy.core.window import Window Window.size = (720, 400) class audiodemoapp(App): length = NumericProperty(0.0) progress = NumericProperty(0.0) def build(self): layout = GridLayout(cols=1, padding=10) self.prg = ProgressBar() layout.add_widget(self.prg) self.l1 = Label( text=”Press Start to Play”, font_size=40, color=[.8, .6, .4, 1] ) layout.add_widget(self.l1) box = BoxLayout(orientation=”horizontal”) self.button1 = Button(text=”Start”, font_size=32) self.button2 = Button( text=”Pause”, font_size=32, disabled=True ) box.add_widget(self.button1) box.add_widget(self.button2) layout.add_widget(box) self.button1.bind(on_press=self.start_stop) self.button2.bind(on_press=self.pause_resume) return layout def start_stop(self, event): if self.button1.text == ”Start”: self.l1.text = ”Playing” self.button1.text = ”Stop” self.sound = SoundLoader.load(”sample.mp3”) self.length = self.sound.length self.pos = 0 self.button2.disabled = False self.sound.play() self.prog_ev = Clock.schedule_interval(self.update_progress, 1.0) else: if self.button1.text == ”Stop”: self.l1.text = ”Press Start to Play” self.sound.state = ”stop” self.button1.text = ”Start” self.sound.unload() self.button2.disabled = True self.pos = 0 def pause_resume(self, event): if self.button2.text == ”Pause”: self.button2.text = ”Resume” self.l1.text == ”Paused” self.pos = self.sound.get_pos() self.sound.stop() else: if self.button2.text == ”Resume”: self.l1.text = ”Playing” self.button2.text = ”Pause” print(self.pos) self.sound.seek(self.pos) self.sound.play() self.prog_ev = Clock.schedule_interval(self.update_progress, 1.0) def update_progress(self, dt): if self.sound.state == ”play”: if self.prg.value < self.length: self.progress += 1 # Update value self.prg.value = self.progress else: # End case. self.progress = 0 # Reset value self.prog_ev.cancel() # Stop updating audiodemoapp().run() Output Run the above code. Press the start button. The progress bar on top shows the instantaneous playing position of the the music file. Print Page Previous Next Advertisements ”;

Kivy – Accordion

Kivy – Accordion ”; Previous Next This GUI widget, because of its resemblance with a musical instrument of the same name, is called the “accordion”. In Kivy, an Accordion is a graphical control element comprising a vertically or horizontally stacked list of items, such as labels or buttons or images. Just as in a musical accordion in which sections of the bellows can be expanded by pulling outward, each item can be “expanded” or “collapsed” to reveal the content associated with that item. There can be zero expanded items, exactly one, or more than one item expanded at a time, depending on the configuration. An accordion is similar in purpose to a tabbed panel, a list of items where exactly one item is expanded into a panel. There are two important classes – “Accordion” and “AccordionItem” – in the “kivy.uix.accordion” module. Each AccordianItem object holds any one Kivy widget such as a label, a button an image or even other layout object. Multiple AccordioItems are then added to the main Accordion object. Following properties/methods are supported by Accordion class − title − Title string of the AccordionItem. min_space − Minimum space to use for the title of each item. This value is automatically set for each child every time the layout event occurs. It is a NumericProperty and defaults to 44 (px). orientation − Orientation of the Accordion layout. Can be either vertical or horizontal. collapse − Boolean property to indicate if the current item is collapsed or not. Example 1 In the following code, an Accordion object is used as the root widget of the Application window. A label, a button and an Image widget is respectively added to each of its AccordionItem widgets. The complete code is given below − from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.label import Label from kivy.uix.image import Image from kivy.uix.accordion import Accordion, AccordionItem from kivy.core.window import Window Window.size = (720,400) class accordiandemoapp(App): def build(self): acc=Accordion(orientation=”horizontal”) item1=AccordionItem(title=”Text Panel”) item1.add_widget(Label(text=”Hello World”)) item2=AccordionItem(title=”Button Panel”) self.btn=Button(text=”ok”) item2.add_widget(self.btn) item3=AccordionItem(title=”Image Panel”) img = Image() img.source=”kivy-logo.png” item3.add_widget(img) acc.add_widget(item1) acc.add_widget(item2) acc.add_widget(item3) return acc accordiandemoapp().run() Output Run the above program and click the Image Panel, to unveil its contents, it being the Kivy logo. You can further expand the other panels by clicking them. Example 2 (using “kv” script) We remove all the statements in build() method, replace it by a pass statement, and then save the following script as accordiondemo.kv file. This time the default orientation of Accordion is changed to vertical. BoxLayout: orientation: “vertical” size: root.width, root.height Accordion: orientation: ”vertical” AccordionItem: title: “Button Panel” Button: text: ”OK” AccordionItem: title: “Text Panel” Label: text: “Hello World” font_size: 32 AccordionItem: title: “Image Panel” Image: source: ”kivy-logo.png” Output The button panel is expanded after running the program − Print Page Previous Next Advertisements ”;

Kivy – Windows

Kivy – Windows ”; Previous Next The Window class is one of the core classes in the Kivy framework. The application window is constructed with placement of one or more widgets in a certain layout. The build() method normally returns a single root widget, which may be a combination of multiple other widgets arranged in a tree. Instead, the root of the widget tree can be directly added to the application window. The Window class is defined in the “kivy.core.window” module. It inherits the WindowBase class which is an abstract window widget for any window implementation. A default application window is created with the App object starting its event loop. Note that Kivy supports only one window per application. Many of the Window properties are read from the Kivy config file (“config.ini” file in KIVY_HOME directory). The widget dimensions depend upon the size of the default window. The following code in the build() method of App class puts a widget tree in the application window. Note that the root widget is not returned by the build() method. Instead it is added to the Window object”s add_widget() method. box=BoxLayout(orientation=”vertical”) l=Label(text=”Window Properties”, font_size=32) box.add_widget(l) b1=ToggleButton(text=”Fullscreen”) b2=ToggleButton(text=”Border”) b3=ToggleButton(text=”Position”) bh=BoxLayout(orientation=”horizontal”, size_hint=(1, .2)) bh.add_widget(b1) bh.add_widget(b2) bh.add_widget(b3) box.add_widget(bh) Window.add_widget(box) Events The Window object can recognize different type of events − The on_motion event is fired when a new MotionEvent is dispatched. Window absorbs the touch events on_touch_down, on_touch_move, on_touch_up etc. The on_close event is fired when the Window is closed. The on_request_close event occurs when the user wants to end the event loop by pressing the close button on the title bar. The on_cursor_enter event is fired when the cursor enters the window. Similarly, the on_cursor_leave event occurs when the cursor leaves the window. The on_minimize and on_maximize events are fired when the window is minimized and maximized respectively. The on_restore event Fires when the window is restored. Similar to touch events, the key events on_key_down and on_key_up events emit the key, scancode, codepoint, modifier when a key is pressed or released respectively. For the demonstration example in this chapter, let us bind some of the Window events with callback methods. Window.bind(on_request_close = self.on_close) Window.bind(on_cursor_leave=self.on_leave) Window.bind(on_cursor_enter=self.on_enter) The on_leave() method is called whenever the mouse pointer leaves the window area. def on_leave(self, *args): print (“leaving the window”) Similarly, when the mouse enters the window area, the on_enter callback is invoked. def on_enter(self, *args): print (“Entering the window”) The on_request_close event is raised when the user chooses to close the event loop. If the user presses X button, the following callback asks the user if he wants to quit. You can also make a popup window to appear. def on_close(self, instance): resp=input(“Do you want the window to close?”) if resp==”y”: Window.close() Properties The appearance of the application window is decided by many properties defined in the Window class. Their default values are provided by the config.ini file. However, they can be modified in the application code. Some of the Wiindow properties are as below − borderless − When set to True, this property removes the window border/decoration. children − returns the List of the children of this window. clearcolor − Color used to clear the window. The clear() method uses this property with this color value from kivy.core.window import Window Window.clearcolor = (1, 0, 0, 1) Window.clear() custom_titlebar − When set to True, allows the user to set a widget as a titlebar. fullscreen − This property sets the fullscreen mode of the window. Available options are: True, False, ”auto” and ”fake”. left , top − Left and Top position of the window. It”s an SDL2 property with [0, 0] in the top-left corner. size − gets/sets the size of the window. from kivy.core.window import Window Window.size = (720,400) You can also set the size by modifying the config values − from kivy.config import Config Config.set(”graphics”, ”width”, ”720”) Config.set(”graphics”, ”height”, ”400”) Config.set(”graphics”, ”resizable”, ”1”) Let us handle some Window properties. On the application window of this program, we have three toggle buttons. We bind them to certain callbacks. b1.bind(on_press=self.pressed) b2.bind(on_press=self.bordered) b3.bind(on_press=self.positioned) The pressed() method toggles the fullscreen state between full screen and normal. def pressed(self, instance): if instance.state==”down”: Window.set_title(“Kivy Full screen window”) Window.maximize() elif instance.state==”normal”: Window.set_title(”Kivy Restored Window”) Window.restore() The bordered() method makes the window borderless when the b2 button is pressed, and back to original bordered window when released. def bordered(self, instance): print (Window.top, Window.left) if instance.state==”down”: Window.borderless=True elif instance.state==”normal”: Window.borderless=False The positioned() callback moves the window to (0,0) position and back to its earlier position when b3 is pressed/released. def positioned(self, instance): print (Window.top, Window.left) if instance.state==”down”: self.x, self.y=Window.left, Window.top Window.left, Window.top=(0,0) elif instance.state==”normal”: Window.left, Window.top=self.x,self.y The Application window appears as below in the first place. Generate the events (mouse leave, entered on request_close) and see the callbacks in action. Similarly check the action of togglebuttons. Print Page Previous Next Advertisements ”;

Kivy – Checkbox

Kivy – Checkbox ”; Previous Next In any GUI toolkit, a checkbox is used to enable the user to select one or choices from the available options. In Kivy, the CheckBox can be configured to make the choice mutually exclusive (only one of the available options is selectable), or let the user mark any number of choices. If two or more checkboxes have the same value for group property, they appear as a circular radiobutton; user can choose only one option, as the active property of only one checkbox can be True, for others active property will be automatically False. For the checkboxes not having the group property, it appears as a rectangular box which when pressed, shows a checkmark with active property becoming True. Click it again and the check marks is removed, the active property becomes False. The CheckBox class is defined in kivy.uix.checkbox module from kivy.uix.checkbox import CheckBox cb = CheckBox(**kwargs) If the checkbox object is be bound to its active property, a callback can be invoked every time the active property changes. checkbox = CheckBox() checkbox.bind(active=callback) Example The following Python code shows how to use checkboxes that are mutually exclusive, as well as multi-selectable. The code uses a vertical BoxLayout with two horizontal layouts and two labels in it. The upper horizontal layout holds two checkboxes with group property of both as ”sex” self.m = CheckBox(group=”sex”, color=[1,0,1,1]) self.m.bind(active=self.on_male) gendergrp.add_widget(self.m) gendergrp.add_widget(Label(text=”Female”)) self.f = CheckBox(active=False, group=”sex”) self.f.bind(active=self.on_female) gendergrp.add_widget(self.f) Both the checkboxes invoke a callback method that identifies the active property. The lower horizontal box holds three independent checkboxes − interests.add_widget(Label(text=”Sports”)) self.cb1 = CheckBox() self.cb1.bind(active=self.on_interest) interests.add_widget(self.cb1) self.cb2 = CheckBox() self.cb2.bind(active=self.on_interest) interests.add_widget(Label(text=”Music”)) interests.add_widget(self.cb2) self.cb3 = CheckBox() self.cb3.bind(active=self.on_interest) interests.add_widget(Label(text=”Travel”)) interests.add_widget(self.cb3) When each of these checkboxes are clicked, a list of selected interests is built and displayed on the label below the horizontal box. Here is the complete code − from kivy.app import App from kivy.uix.label import Label from kivy.uix.checkbox import CheckBox from kivy.uix.boxlayout import BoxLayout from kivy.core.window import Window Window.size = (720,400) class CheckBoxApp(App): gender=”” intrst=[] def on_male(self, instance, value): if value: CheckBoxApp.gender=”Male” self.lbl.text = “Gender selected: “+CheckBoxApp.gender else: self.lbl.text = “Gender selected: “ def on_female(self, instance, value): if value: CheckBoxApp.gender=”Female” self.lbl.text = “Gender selected: “+CheckBoxApp.gender else: self.lbl.text = “Gender selected: “ def on_interest(self, instance, value): CheckBoxApp.intrst=[] if self.cb1.active: CheckBoxApp.intrst.append(“Sports”) if self.cb2.active: CheckBoxApp.intrst.append(“Music”) if self.cb3.active: CheckBoxApp.intrst.append(“Travel”) self.lbl1.text=”Interests Selected: “+” “.join(CheckBoxApp.intrst) def build(self): main=BoxLayout(orientation=”vertical”) gendergrp=BoxLayout(orientation=”horizontal”) interests = BoxLayout(orientation=”horizontal”) gendergrp.add_widget(Label(text=”Gender:”)) gendergrp.add_widget(Label(text=”Male”)) self.m = CheckBox(group=”sex”, color=[1,0,1,1]) self.m.bind(active=self.on_male) gendergrp.add_widget(self.m) gendergrp.add_widget(Label(text=”Female”)) self.f = CheckBox(active=False, group=”sex”) self.f.bind(active=self.on_female) gendergrp.add_widget(self.f) main.add_widget(gendergrp) self.lbl = Label(text=”Gender selected: “, font_size=32) main.add_widget(self.lbl) interests.add_widget(Label(text=”Interests:”)) interests.add_widget(Label(text=”Sports”)) self.cb1 = CheckBox() self.cb1.bind(active=self.on_interest) interests.add_widget(self.cb1) self.cb2 = CheckBox() self.cb2.bind(active=self.on_interest) interests.add_widget(Label(text=”Music”)) interests.add_widget(self.cb2) self.cb3 = CheckBox() self.cb3.bind(active=self.on_interest) interests.add_widget(Label(text=”Travel”)) interests.add_widget(self.cb3) self.lbl1 = Label(text=”Interests selected: “, font_size=32) main.add_widget(interests) main.add_widget(self.lbl1) return main if __name__ == ”__main__”: CheckBoxApp().run() Output When you run this code, it will produce a GUI like the one shown here − Print Page Previous Next Advertisements ”;

Kivy – Carousel

Kivy – Carousel ”; Previous Next A carousel is a slideshow for cycling through a series of content. The Kivy framework includes a Carousel widget that allows you to easily create a browsable slideshow, particularly useful for touchscreen devices such as smartphones. The pages in a carousel can be moved horizontally or vertically. The Carousel class is defined in the “kivy.uix.carousel” module. from kivy.uix.carousel import Carousel carousel = Carousel(**kwargs) A Python/Kivy program to create a simple slideshow with carousel is given below − from kivy.app import App from kivy.uix.carousel import Carousel from kivy.uix.image import Image class CarouselApp(App): def build(self): carousel = Carousel(direction=”right”) img1=Image(source=”1.png”) carousel.add_widget(img1) img2=Image(source=”2.png”) carousel.add_widget(img2) img3=Image(source=”3.png”) carousel.add_widget(img3) return carousel CarouselApp().run() You can also employ a “kv” language script to construct a carousel. Carousel: direction: ”right” Image: source: ”1.png” Image: source: ”2.png” Image: source: ”3.png” Image: source: ”4.png” The Carousel class defines following properties − current_slide − The currently shown slide. current_slide is an AliasProperty. direction − Specifies the direction in which the slides are ordered. This corresponds to the direction from which the user swipes to go from one slide to the next. It can be right, left, top, or bottom. index − Get/Set the current slide based on the index. index defaults to 0 (the first item). load_next(mode=”next”) − Animate to the next slide. load_previous() − Animate to the previous slide. load_slide(slide) − Animate to the slide that is passed as the argument. loop − Allow the Carousel to loop infinitely. If True, when the user tries to swipe beyond last page, it will return to the first. If False, it will remain on the last page. next_slide − The next slide in the Carousel. It is None if the current slide is the last slide in the Carousel. previous_slide − The previous slide in the Carousel. It is None if the current slide is the first slide in the Carousel. scroll_distance − Distance to move before scrolling the Carousel in pixels. Default distance id 20dp. scroll_timeout − Timeout allowed to trigger the scroll_distance, in milliseconds. Defaults to 200 (milliseconds) slides − List of slides inside the Carousel. Example As an example of Carousel in Kivy, have a look at the following code. The Carousel object is used as the root widget of the app, and we add a label, a button and an image as its slides. from kivy.app import App from kivy.uix.button import Button from kivy.uix.carousel import Carousel from kivy.uix.image import Image from kivy.core.window import Window Window.size = (720,350) class CarouselApp(App): def build(self): carousel = Carousel(direction=”right”) carousel.add_widget(Button(text=”Button 1”, font_size=32)) src = “ganapati.png” image = Image(source=src, fit_mode=”contain”) carousel.add_widget(image) carousel.add_widget(Button(text=”Button 2″, font_size=32)) return carousel CarouselApp().run() Output This is a simple app to browse a series of slides by swiping across the display of your device. The direction parameter is set to right, which means that the subsequent slides are towards right. Assembling the Carousel using “kv” Language Let”s use the “kv” language script to assemble the carousel. This time, the direction is set to top, which means you have to swipe up the screen to see the next display. Example Carousel: direction:”top” Button: text:”Button 1” font_size:32 Image: source:”kivy-logo.png” fit_mode:”contain” Button: text:”Button 2″ font_size:32 Output The slides are stacked one above the other. Print Page Previous Next Advertisements ”;

Kivy – File Chooser

Kivy – File Chooser ”; Previous Next In a GUI application, you are often required to choose a required file from the local filesystem. Kivy framework presents the “kivy.uix.filechooser” module that provides various classes for describing, displaying and browsing file systems. The classes in filechooser module adopt a MVC design. They can be categorized as follows − Models are represented by concrete implementations of the FileSystemAbstract class, such as the FileSystemLocal. Views are represented by the FileChooserListLayout and FileChooserIconLayout classes. These are used by the FileChooserListView and FileChooserIconView widgets respectively. Controllers are represented by concrete implementations of the FileChooserController, namely the FileChooser, FileChooserIconView and FileChooserListView classes. The FileChooserIconView and FileChooserListView classes provide very-simple-to-use widgets that provide access to the file system with two different visual representations, as the names suggest. The FileChooserListView widget displays files and folders as text items in a vertical list. A folder is identified by a “>” sign to the left of its name, and a click expands or collapses its files and subfolders. The FileChooserIconView widget displays a folder icon with the name below it, and a file icon with its name. If the number of files/folders exceeds the height and width of the widget, the vertical and horizontal scrollbars are attached to it. The FileChooser views have following properties − files − The list of files in the directory specified by path after applying the filters. files is a read-only ListProperty. filter_dirs − Indicates whether filters should also apply to directories. filter_dirs is a BooleanProperty and defaults to False. filters − filters specifies the filters to be applied to the files in the directory. filters is a ListProperty and defaults to []. If empty, it is equivalent to ”*” indicating that no file has been filtered out of the list. The filters are not reset when the path changes. You need to do that yourself if desired. You can specify one or more of the following patterns in the list − Sr.No Patterns List & Description 1 * matches everything 2 ? matches any single character 3 [seq] matches any character in seq 4 [!seq] matches any character not in seq Both the views raise the on_selection event to which a callback can be bound. When this event is generated, if a folder is selected, it will expand or collapse it. If a file is selected, its name is passed to the callback. ListView Example In the first example, we construct the App window with a FileChhoserListView widget and a label in a vertical box layout. Use the following “kv” file script for the purpose. The select() method is bound to the view”s “on_selection” event. <Filechooser>: label: label orientation: ”vertical” BoxLayout: FileChooserListView: canvas.before: Color: rgb: .4, .5, .5 Rectangle: pos: self.pos size: self.size on_selection: root.select(*args) Label: id: label size_hint_y: .1 canvas.before: Color: rgb: .5, .5, .4 Rectangle: pos: self.pos size: self.size Note the use of canvas object of FileChooseListView and Label widgets to provide background color. The Kivy Application class code is given below − from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.core.window import Window Window.size = (720,400) class Filechooser(BoxLayout): def select(self, *args): try: self.label.text = args[1][0] except: pass class FileDemoApp(App): def build(self): return Filechooser() if __name__ == ”__main__”: FileDemoApp().run() Output When the above code is run, you get the list of files/folders. The name of the file with its full path is displayed on the label. IconView Example We now show the use of FileChooserIconView. It is placed in a horizontal box, along with an Image widget by its side. While most of the configuration of FileChooserIconView is same as in previous example, we add the filters property to restrict the display of files to png files only. <Filechooser>: img: img orientation: ”horizontal” BoxLayout: FileChooserIconView: filters: [”*.png”] canvas.before: Color: rgb: .5, .4, .5 Rectangle: pos: self.pos size: self.size on_selection: root.select(*args) Image: id: img source:”” Since we intend to display the selected image, the select() method is changed so that the source property of Image object is assigned with the selected file. class Filechooser(BoxLayout): def select(self, *args): try: self.img.source = args[1][0] except: print (”error”) class FileIconApp(App): def build(self): return Filechooser() # run the App if __name__ == ”__main__”: FileIconApp().run() Output Run the program and browse to the desired image file. The selected image will be displayed on the right. Print Page Previous Next Advertisements ”;