Kivy – Box Layouts

Kivy – Box Layouts ”; Previous Next Kivy framework provides BoxLayout class with which we can arrange the widgets sequentially. The sequence is determined by the orientation property of BoxLayout object and can be a string: either ”vertical” or ”horizontal”. The BoxLayout class is defined in the “kivy.uix.boxlayout” module. To declare a BoxLayout object, use. from kivy.uix.boxlayout import BoxLayout blo = BoxLayout(**kwargs) Properties orientation − Orientation of the layout. orientation is an OptionProperty and defaults to ”horizontal”. Can be ”vertical” or ”horizontal”. padding − Padding between layout box and children: [padding_left, padding_top, padding_right, padding_bottom]. padding also accepts a two argument form [padding_horizontal, padding_vertical] and a one argument form [padding]. 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. The BoxLayout class also inherits the add_widget() and remove_widget() methods, which we have already discussed earlier. Vertical BoxLayout Typical use of BoxLayout is shown here. We add a label, a text input and a button in a vertical box layout. Example 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.boxlayout import BoxLayout from kivy.core.window import Window Window.size = (720,200) class DemoApp(App): def build(self): lo = BoxLayout(orientation = ”vertical”) self.l1 = Label(text=”Enter your name”, font_size=20) self.t1 = TextInput(font_size = 30) self.b1 = Button(text = ”Submit”, size_hint = (None, None),pos_hint={”x”:.4, ”y”:.2}, size = (200,75)) lo.add_widget(self.l1) lo.add_widget(self.t1) lo.add_widget(self.b1) return lo if __name__ == ”__main__”: DemoApp().run() Output It will produce the following output − You can use the following “Demo.kv” file to construct the above GUI − BoxLayout: orientation : ”vertical” Label: id : l1 text : ”Enter your name” font_size : ”20pt” TextInput: id : t1 font_size : 30 Button: id : b1 text : ”Submit” size_hint : (None, None) pos_hint : {”x”:.4, ”y”:.2} size : (200,75) Horizontal BoxLayout In the following program, we have placed a label, a text input box and a button in Box layout with horizontal orientation. Example 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.boxlayout import BoxLayout from kivy.clock import Clock from kivy.core.window import Window Window.size = (720,200) class DemoApp(App): def build(self): self.lo = BoxLayout(orientation = ”horizontal”) self.l1 = Label(text=”Enter your name”, font_size=20) self.t1 = TextInput(font_size = 30, pos_hint={”y”:0.25}, pos = (0,100), size_hint = (None, None), size = (650,100)) self.b1 = Button(text = ”Submit”, size_hint = (None, None),pos_hint={”x”:.4, ”y”:.35}, size = (75, 40)) self.lo.add_widget(self.l1) self.lo.add_widget(self.t1) self.lo.add_widget(self.b1) return self.lo if __name__ == ”__main__”: DemoApp().run() Output It will produce the following output − You can obtain the same GUI design with the following “Demo.kv” file − BoxLayout: orientation : ”horizontal” Label: text : ”Enter your name” font_size : ”20pt” TextInput : font_size : ”30pt” pos_hint : {”y”:0.25} pos : (0,100) size_hint : (None, None) size : (650,100) Button : text : ”Submit” size_hint : (None, None) pos_hint : {”x”:.4, ”y”:.35} size : (75, 40) Print Page Previous Next Advertisements ”;

Kivy – Settings

Kivy – Settings ”; Previous Next The “kivy.uix.settings” module includes a very useful feature that lets you to handle the setting parameters of your Kivy installation environment. You can open the Settings panel on the application window and modify any of the configuration tokens. When Kivy software is installed, it creates a configuration file that contains various parameter tokens with their default values. The file, named as “config.ini”, is stored in a directory identified by KIVY_HOME environment variable. On a Windows machine − The file is stored at C:Usersuser.kivyconfig.ini. On Linux − /home/user/.kivy/config.ini. On macOS − /Users/user/.kivy/config.ini. On Android − /data/data/org.kivy.launcher/files/.kivy/config.ini. On iOS − <HOME_DIRECTORY>/Documents/.kivy/config.ini. To open the settings panel, call the open_settings() method of the App class, usually in response to an on_press event (or any other event) on the GUI. def onpress(self, instance): app.open_settings() We start with a simple Kivy app with a Button mounted on the window. When the button is presses, it calls the onpress() method to display the Kivy settings panel. class HelloApp(App): def onpress(self, instance): app.open_settings() def build(self): b1=Button( text=”Click Here”, font_size=50, on_press=self.onpress ) return b1 app = HelloApp() app.run() After the application is run, click the button to enter into the settings panel. The settings shown here are the same that you see in the config.ini file. Try changing value of any of the config tokens, and you will see the changes done to the config file. There are several setting panel layouts available. Settings − Displays settings with a sidebar at the left to switch between json panels. SettingsWithSidebar − A trivial subclass of Settings. SettingsWithSpinner − Displays settings with a spinner at the top, which can be used to switch between json panels. This is the default. SettingsWithTabbedPanel − Displays json panels as individual tabs in a TabbedPanel. SettingsWithNoMenu − Displays a single json panel, with no way to switch to other panels and no close button. To use the SeetingsWithSidebar layout, import it from the kivy.uix.settings module and assign it as the value for settings_cls parameter of the App class. from kivy.uix.settings import SettingsWithSidebar class HelloApp(App): def onpress(self, instance): app.open_settings() def build(self): self.settings_cls = SettingsWithSidebar b1=Button(text=”Click Here”, font_size=50, on_press=self.onpress) return b1 The window now provides a sidebar to switch between settings panels. Create a New Panel Right now, you have only a panel titled Kivy that diaplays the default settings of Kivy”s configuration. You can add a new panel to define the settings for your app. You need two things − a ConfigParser instance with default values. a JSON object. You must create and handle the ConfigParser object to tell kivy”s configparser what settings to store in a config file.. SettingsPanel will read the values from it. The default values of these settings are specified with setdefaults for all the sections/keys in your JSON object. Let us add build_config method that gives the default values for button” text and font_size properties. def build_config(self, config): config.setdefaults(”My Button”, {”text”: ”Hello Kivy, ”font_size”: 20}) The build_settings() method builds a new panel in the configuration from the JSON object in the code. The JSON object used in this example is − json = ””” [ { “type”: “string”, “title”: “Button text”, “desc”: “text on the button”, “section”: “My Button”, “key”: “text” }, { “type”: “numeric”, “title”: “Button font size”, “desc”: “font size”, “section”: “My Button”, “key”: “font_size” } ] To add a new panel based on the definition of this JSON object define build_settings() method − def build_settings(self, settings): settings.add_json_panel(”My Button”, self.config, data=json) And that”s all. When you open the settings, you should see a new My Button panel added. Example The complete code is given below − from kivy.app import App from kivy.uix.button import Button from kivy.core.window import Window from kivy.uix.settings import SettingsWithSidebar Window.size = (720,350) json = ””” [ { “type”: “string”, “title”: “Button text”, “desc”: “text on the button”, “section”: “My Button”, “key”: “text” }, { “type”: “numeric”, “title”: “Button font size”, “desc”: “font size”, “section”: “My Button”, “key”: “font_size” } ] ””” class MyApp(App): def onpress(self, instance): app.open_settings() def build(self): self.settings_cls = SettingsWithSidebar self.btn = Button(on_press=self.onpress) self.btn.text = self.config.get(”My Button”, ”text”) self.btn.font_size = float(self.config.get(”My Button”, ”font_size”)) return self.btn def build_config(self, config): config.setdefaults( ”My Button”, {”text”: ”Hello Python”, ”font_size”: 20} ) def build_settings(self, settings): settings.add_json_panel(”My Button”, self.config, data=json) def on_config_change(self, config, section, key, value): if section == “My Button”: if key == “text”: self.btn.text = value elif key == ”font_size”: self.btn.font_size = float(value) app=MyApp() app.run() Output When you open the settings panel, you now see the My Button Panel with two settings. Modify the values as required. Finally, close the settings dialog and go back to see the changes. Print Page Previous Next Advertisements ”;

Kivy – Text Markup

Kivy – Text Markup ”; Previous Next Although Kivy”s Label object has properties such as bold, italics and color, etc., it also provides markup facility to decorate the label text using a syntax similar to HTML tags. For the markup to show effect, you need to set the markup property of the label to True. l = Label(text=”Hello [b]World[/b]”, markup=True) Note that the kivy markup can be used only for inline styling. Instead of the tags with angular brackets as in HTML (as <b>Hello</b>), square brackets are used here (example: [b]Hello</b]) The text with this markup syntax is very much similar to the HTML syntax, as the following table shows − HTML Kivy Markup <b>bolded text</b> [b]bolded text[/b] <i>italicized text</i> [i]italicized text[/i] <u>underlined text</u> [u]underlined text[/u] The following tags can be used for inline styling of the text property of label widget − Sr.No Text Property & Description 1 [b][/b] Activate bold text 2 [i][/i] Activate italic text 3 [u][/u] Underlined text 4 [s][/s] Strikethrough text 5 [font=<str>][/font] Change the font (str should be name of TTF file) 6 [font_family=<str>][/font_family] Font family to request for drawing. 7 [size=<size>][/size] Change the font size. <size> should be an integer. 8 [color=#<color>][/color] Change the text color 9 [anchor=<str>] Put an anchor in the text. 10 [sub][/sub] Display the text at a subscript position relative to the text before it. 11 [sup][/sup] Display the text at a superscript position relative to the text before it. If you need to escape the markup from the current text, use kivy.utils.escape_markup(). Print Page Previous Next Advertisements ”;

Kivy – Popup

Kivy – Popup ”; Previous Next A Popup widget in Kivy presents a dialog that appears over the main Prent window, usually in response to a button-click event. A dialog box is used for many purposes, such as displaying a certain message to the user, making the user enter some input, or asking the user to confirm a particular action. In general, the dialogs in any GUI application are of two types: modal and non-modal. A dialog box that doesn”t allow the user to interact with the parent window without interacting with it, is called a modal dialog. On the other hand, if the user can dismiss the dialog box without interacting with it, it is a non-modal dialog. In Kivy, the popup dialog covers the entire parent window by default. How you can configure its size as required. The Popup class is defined in the “kivy.uix.popup” module. from kivy.uix.popup import Popup popup = Popup(**kwargs) A Popup object is preconfigured with a layout that has a title and a separation bar. We can customize the layout by adding other widgets to its layout parameter. The following snippet produces a simple popup over the parent window − from kivy.uix.popup import Popup popup = Popup(title=”Popup Demo”, content=Label(text=”This is a Popup”), size_hint=(None, None), size=(400, 400)) You need to call the open() method of Popup object to display it. popup.open() As the pop is displayed, it will be dismissed by any click outside it. To prevent the popup from getting automatically dismissed, set the auto_dismiss property to False. You need to call the popup.dismiss() method explicitly. Usually, this is done by binding it to a button”s on_press event. class popdemo(App): def build(self): btn = Button(text=”Click here”) btn.bind(on_press=self.onButtonPress) return btn def onButtonPress(self, button): layout = GridLayout(cols=1) lbl = Label(text=”Hello world”) closeButton = Button(text=”OK”) layout.add_widget(lbl) layout.add_widget(closeButton) popup = Popup( title=”Popup Demo”, content=layout, auto_dismiss=False, size_hint=(None, None), size=(400, 400) ) popup.open() closeButton.bind(on_press=self.on_close) def on_close(self, event): self.popup.dismiss() When the button captioned “Click here” is clicked, you get a popup dialog as shown below − Press the OK button on the popup to dismiss it. The Popup class defines following properties − content − Content of the popup that is displayed just under the title. content is an ObjectProperty and defaults to None. title − String that represents the title of the popup. title is a StringProperty and defaults to ”No title”. A Popup object responds to the following events − on_open − Fired when the Popup is opened. on_dismiss − Fired when the Popup is closed. If the callback returns True, the dismiss will be canceled. Example The following code gives a good example of Popup dialog in Kivy. First of all, we add a label and a button to the vertical box layout of a parent window. The button click pops up a one-column gridlayout with a text input, asking the user to enter name. As the popup is dismissed, the text is used to change the label of the parent window. Here is the complete code − from kivy.app import App from kivy.uix.button import Button from kivy.uix.label import Label from kivy.uix.textinput import TextInput from kivy.uix.gridlayout import GridLayout from kivy.uix.popup import Popup from kivy.core.window import Window Window.size = (720, 400) class PopupExample(App): def build(self): self.layout = GridLayout(cols=1, padding=10) self.l1 = Label( text=”enter your name”, font_size=32, color=[.8, .6, .4, 1] ) self.layout.add_widget(self.l1) self.button = Button(text=”Click Here”) self.layout.add_widget(self.button) self.button.bind(on_press=self.onButtonPress) return self.layout def onButtonPress(self, button): layout = GridLayout(cols=1, padding=10) popupLabel = Label(text=”Enter name”) self.t1 = TextInput() closeButton = Button(text=”OK”) layout.add_widget(popupLabel) layout.add_widget(self.t1) layout.add_widget(closeButton) self.popup = Popup( title=”Hello”, content=layout, auto_dismiss=False, size_hint=(None, None), size=(200, 200) ) self.popup.open() closeButton.bind(on_press=self.on_close) def on_close(self, event): self.l1.text = ”Thanks ” + self.t1.text self.popup.dismiss() PopupExample().run() Output The App window appears like this − Print Page Previous Next Advertisements ”;

Kivy – Float Layout

Kivy – Float Layout ”; Previous Next In Kivy, FloatLayout gives you complete control over the placement of widgets. It enforces no restrictions on how a widget is positioned and how it is sized. FloatLayout honors the “pos_hint” and the “size_hint” properties of its children. The FloatLayout class is defined in the “kivy.uix.floatlayout” module. from kivy.uix.floatlayout import FloatLayout layout = FloatLayout(**kwargs) You can specify the layout size with size parameter. It is a tuple of width and height in pixels. layout = FloatLayout(size=(300, 300)) When a widget is placed in a FloatLayout object with add_widget() method, will adopt the same size as the layout. You can specify “size_hint”, “pos_hint”, “pos” and “size” properties to define the size and position of a widget in FloatLayout. button = Button( text=”TutorialsPoint”, size_hint=(.4, .3), pos=(100, 100)) This will position a button at 100,100 coordinates (measured from bottomleft) and of size 40% of the layout width, 30% of layout height. FloatLayout supports the two main methods, inherited from the Widget class: add_widget() and remove_widget(). The basic usage of FloatLayout is shown below − class FloatApp(App): def build(self): flo = FloatLayout() l1 = Label(text=”TutorialsPoint”) flo.add_widget(l1) return flo You can also use the “kv” file to populate the application window as shown below − FloatLayout: Label: text : ”TutorialsPoint” Example Let us design a form with three labels, three text input boxes − one which is a multiline text box, and a submit button. A FloatLayout object is used for the purpose. The labels are placed at 200 px as x-coordinate value, the text boxes at 400 px as x coordinate value. Labels and text boxes have width that is 10% of the layout. The single button is placed horizontally in the center. 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.floatlayout import FloatLayout from kivy.graphics import Color, Rectangle from kivy.core.window import Window Window.size = (720,350) class FloatApp(App): def build(self): flo = FloatLayout() l1 = Label( text=”Name”, size_hint=(.2, .1), pos=(200, 350), color = [1,1,1,1] ) with l1.canvas: Color(0, 1, 0, 0.25) Rectangle(pos=l1.pos, size=(350, 50)) flo.add_widget(l1) t1 = TextInput(size_hint=(.4, .1), pos=(400, 350)) flo.add_widget(t1) l2 = Label( text=”Address”, size_hint=(.2, .1), pos=(200, 250),color = [1,1,1,1] ) with l2.canvas: Color(0, 1, 0, 0.25) Rectangle(pos=l2.pos, size=(350, 50)) flo.add_widget(l2) t2 = TextInput( multiline=True, size_hint=(.4, .1), pos=(400, 250) ) flo.add_widget(t2) l3 = Label( text=”College”, size_hint=(.2, .1), pos=(200, 150), color = [1,1,1,1] ) with l3.canvas: Color(0, 1, 0, 0.25) Rectangle(pos=l3.pos, size=(350, 50)) flo.add_widget(l3) t3 = TextInput(size_hint=(.4, .1), pos=(400, 150)) flo.add_widget(t3) b1 = Button( text=”Submit”, size_hint = (.2, .1), pos_hint = {”center_x”:.5, ”center_y”:.09} ) flo.add_widget(b1) return flo FloatApp().run() Output When you run this code, it will produce an output window like this one − Note that the labels are given background color by drawing a rectangle on the label canvas with RGBA color value (0, 1, 0, 0.25). If you wish to use a “kv” file instead of designing the UI in the build() method, here is the “kv” language script − FloatLayout: Label: id:l1 text:”Name” size_hint:(.2, .1) pos:(200, 350) color : [1,1,1,1] canvas: Color : rgba: 0, 1, 0, 0.25 Rectangle: pos:self.pos size : (350, 50) Label: id:l2 text:”Address” size_hint:(.2, .1) pos:(200, 250) color : [1,1,1,1] canvas: Color : rgba: 0, 1, 0, 0.25 Rectangle: pos:self.pos size : (350, 50) Label: id:l3 text:”College” size_hint:(.2, .1) pos:(200, 150) color : [1,1,1,1] canvas: Color : rgba: 0, 1, 0, 0.25 Rectangle: pos:self.pos size : (350, 50) TextInput: id:t1 size_hint:(.4, .1) pos:(400, 350) TextInput: id:t2 multiline:True size_hint:(.4, .1) pos:(400, 250) TextInput: id:t3 size_hint:(.4, .1) pos:(400, 150) Button: id:b1 text:”Submit” size_hint : (.2, .1) pos_hint : {”center_x”:.5, ”center_y”:.09} Print Page Previous Next Advertisements ”;

Kivy – Audio

Kivy – Audio ”; Previous Next Kivy framework provides the Sound class that handles functions like loading audio files, playing and stopping the playback. Sound class is one of the core classes, defined in the “kivy.core.audio” module. It is not advised to instantiate the Sound object directly. Instead, use the SoundLoader function as shown below − from kivy.core.audio import SoundLoader sound = SoundLoader.load(”test.mp3”) Audio playback is handled by Gstreamer implementations: using Gi/Gst and PyGST. Gi/GST works for both Python 2+3 with Gstreamer 1.0, while PyGST working only for Python 2 + Gstreamer 0.10. Note that the core audio library does not support recording audio. If you require this functionality, please refer to the audiostream extension. The Sound object has the following important properties/methods − Sr.No Properties/Methods & Description 1 load() Load the file into memory. 2 play() Play the file. 3 stop() Stop playback. 4 unload() Unload the file from memory. 5 seek(position) Go to the <position> (in seconds). 6 get_pos() Returns the current position of the audio file. Returns 0 if not playing. 7 length Get length of the sound (in seconds). 8 loop Set to True if the sound should automatically loop when it finishes. 9 source Filename / source of your audio file. 10 state State of the sound, one of ”stop” or ”play”. Let us use the Sound object and build a simple audio player in Kivy. The application window houses a label that shows the present status of the player, i.e., whether it is playing or stopped, and two buttons to control the playback. A button on the left is captioned ”Play” to start with. When clicked, it loads the sound object from a mp3 file, calls play() method, changes label caption to ”Playing” and enables the pause button, and its caption changes to ”Stop”. When the left button is clicked while its caption is ”Stop”, the playback is stopped, restores the label caption and disables the pause button. When you hit the Pause button, the current position of audio file is stored in pos variable, the button caption changes to Resume. When it is clicked, the play position is retrieved by calling seek() method. Example Here is the complete code − from kivy.app import App 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.core.window import Window Window.size = (720, 350) class audiodemoapp(App): def build(self): layout = GridLayout(cols=1, padding=10) 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=”Play”, 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 == ”Play”: self.l1.text = ”Playing” self.button1.text = ”Stop” self.sound = SoundLoader.load(”sample.mp3”) self.pos = 0 self.button2.disabled = False self.sound.play() else: if self.button1.text == ”Stop”: self.l1.text = ”Press to Play” self.button1.text = ”Play” 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() print(self.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() audiodemoapp().run() Output The following figure shows the status caption set to ”Playing” and pause button is enabled. The Pause button toggles between Pause and Resume states. Print Page Previous Next Advertisements ”;

Kivy – Switch

Kivy – Switch ”; Previous Next The Switch widget in Kivy framework resembles the electrical switch that we use in our home to put a bulb or a fan ON or OFF. The switch on the app window can be flipped by swiping its active property to True or False. The Switch class is defined in the “kivy.uix.switch: module. from kivy.uix.switch import Switch switch = Switch(**kwargs) When placed on the application window, a Switch object appears like this − The Switch class defines a Boolean property named active, which indicates whether the switch is on/off. Generally, this property is attached to a callback function to invoke a desired action when its value changes from True to False or vice versa. def callback(instance, value): if value: print(”the switch is ON”) else: print (”The switch is OFF”) switch = Switch() switch.bind(active=callback) Example We shall use the Switch widget in the following code to start or stop playing an audio playback. The app design contains a label and a switch placed in a horizontal box layout. The active property of Switch is bound to a switched() method. When ON, the Sound object is loaded and its play() method is called. On the other hand, when flipped to OFF, the stop() method gets invoked. from kivy.app import App from kivy.uix.label import Label from kivy.uix.boxlayout import BoxLayout from kivy.core.audio import SoundLoader from kivy.uix.switch import Switch from kivy.core.window import Window Window.size = (720, 250) class switchdemoapp(App): def switched(self, instance, value): if value == True: self.sound = SoundLoader.load(”sample.mp3”) self.l1.text = ”Playing. . .” self.sound.play() else: self.sound.stop() self.l1.text = ”Switch ON to Play” def build(self): box = BoxLayout(orientation=”horizontal”) self.l1 = Label( text = ”Switch ON to Play”, font_size = 32, color = [.8, .6, .4, 1] ) box.add_widget(self.l1) switch = Switch() switch.bind(active = self.switched) box.add_widget(switch) return box switchdemoapp().run() Output The program starts with the label asking the user to swipe the switch to ON. The label caption changes to ”Playing” message. Swipe the switch to OFF to stop the music from playing. Print Page Previous Next Advertisements ”;

Kivy – Effects

Kivy – Effects ”; Previous Next The Kivy library provides the “kivy.effects” subpackage to control the overscroll effects when using the ScrollView widget in a Kivy app. The Effect classes can perform actions like bouncing back, changing opacity, or prevent scrolling beyond the normal boundaries. There are three Effect classes − ScrollEffect − Base class used for implementing an effect. It only calculates the scrolling and the overscroll. This class is defined in kivy.effects.scroll module DampedScrollEffect − Uses the overscroll information to allow the user to drag more than expected. Once the user stops the drag, the position is returned to one of the bounds. The definition of this class is in kivy.effects.dampedscroll module. OpacityScrollEffect − Uses the overscroll information to reduce the opacity of the scrollview widget. When the user stops the drag, the opacity is set back to 1. The class definition is available in kivy.effects.opacityscroll module. These classes use the KineticEffect as the base class for computing velocity out of a movement. To apply the effect of any of these classes on the scrolling behavior of ScrollView, set one of these classes as the value of effect_cls property of ScrollView widget. scr = ScrollView(size=Window.size) scr.eefect_cls=ScrollEffect Example The following “kv” language script constructs a ScrollView with a hundred buttons added to a GridLayout. The “effect_cls” property is set to ScrollEffect class. #:import ScrollEffect kivy.effects.scroll.ScrollEffect #:import Button kivy.uix.button.Button <RootWidget> effect_cls: ScrollEffect GridLayout: size_hint_y: None height: self.minimum_height cols: 1 on_parent: for i in range(100): self.add_widget(Button(text=str(i), size_hint_y=None)) The above “kv” code uses a class rule by the name RootWidget. The build() method of the App class in the following Python code returns an object of RootWidget class. from kivy.uix.gridlayout import GridLayout from kivy.uix.button import Button from kivy.uix.scrollview import ScrollView from kivy.effects.dampedscroll import DampedScrollEffect from kivy.core.window import Window from kivy.app import App from kivy.core.window import Window Window.size = (720,350) class RootWidget(ScrollView): pass class scrollableapp(App): def build(self): return RootWidget() scrollableapp().run() Output Execute the above Python program from command line. You get the app window with a scrollview, showing a snapshot of buttons. You can scroll up or down with the ScrollEffect activated. You can customize the Effect class by specifying the attributes in the RootWidget class and use it as the “effect_cls” property. For example, you can set the max and min boundaries to be used for scrolling. The overscroll property is the computed value when the user overscrolls, i.e., goes out of the bounds. Print Page Previous Next Advertisements ”;

Kivy – VKeyboard

Kivy – VKeyboard ”; Previous Next The VKeyboard widget in Kivy library is especially useful for applications running on multitouch devices such as smartphones and tablets. VKeyboard is an on-screen keyboard. Its operation is intended to be transparent to the user. The VKeyboard is used in two modes − docked and free mode. The free mode is suitable for multitouch devices, whereas the docked mode is enabled while using a computer like a tablet. The VKeyboard class is defined in kivy.uix.vkeyboard module. from kivy.uix.vkeyboard import VKeyboard kb = VKeyboard(**kwargs) A virtual keyboard is never used directly. Instead, it is controlled by the configuration. If the application has any widget (such as TextInput) that requires a keyboard, do not use the virtual keyboard directly, but prefer to use the best method available on the platform. The VKeyboard class inherits the ScatterLayout. A button in the bottom right of the virtual keyboard widget lets you switch between available layouts. The VKeyboard object has the following properties − available_layouts − Dictionary of all available layouts. Keys are the layout ID, and the value is the JSON, defaults to {}. callback − Callback can be set to a function that will be called if the VKeyboard is closed by the user. docked − Indicate whether the VKeyboard is docked on the screen or not. If you change it, you must manually call setup_mode() otherwise it will have no impact. key_margin − Key margin, used to create space between keys. The margin is composed of four values, in pixels − key_margin = [top, right, bottom, left] key_margin defaults to [2, 2, 2, 2] target − Target widget associated with the VKeyboard. If set, it will be used to send keyboard events. Example In the following example, the initial constitution of a one-column grid layout shows a label and a TextInput widget. As the user generates a touch_down event by clicking inside the text box, a VKeyboard widget is added to the layout. def ontouch(self, instance, value): self.kb = VKeyboard( on_key_up = self.vkbinput, pos_hint={”center_x”:.5}, size_hint=(.8, None) ) self.layout.add_widget(self.kb) When any key on the keyboard is pressed, it generates on_key_up event. It is bound to a vkbinput() method. This method reads the keycode of the depressed key and updates the contents of the text box. def vkbinput(self, keyboard, keycode, *args): text = self.text1.text if keycode == ”~”: self.layout.remove_widget(self.kb) return self.text1.text = f”{text}{keycode}” Whenever the user presses the “~” key, the keyboard widget is removed from the layout. The complete code is given below − from kivy.app import App from kivy.uix.vkeyboard import VKeyboard from kivy.uix.textinput import TextInput from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout from kivy.core.window import Window Window.size = (720, 400) class MainApp(App): def build(self): self.layout = GridLayout(cols=1) self.text1 = TextInput( font_size=32, on_touch_down=self.ontouch ) self.label = Label( text=”Enter Text….”, font_size=32, color=[.8, .6, .1] ) self.layout.add_widget(self.label) self.layout.add_widget(self.text1) return self.layout def ontouch(self, instance, value): self.kb = VKeyboard( on_key_up=self.vkbinput, pos_hint={”center_x”: .5}, size_hint=(.8, None) ) self.layout.add_widget(self.kb) def vkbinput(self, keyboard, keycode, *args): text = self.text1.text if keycode == ”~”: self.layout.remove_widget(self.kb) return self.text1.text = f”{text}{keycode}” MainApp().run() Output When the above code runs, the initial display of the app window is like this − Click inside the textbox, and the virtual keyboard appears below it − You can now enter the text. Press “~” to remove the keyboard. Print Page Previous Next Advertisements ”;

Kivy – Stencil View

Kivy – Stencil View ”; Previous Next The StencilView widget in Kivy library limits the canvas area of other children widgets added to it. Any instructions trying to draw outside the stencil view area will be clipped. Stencil graphics instructions are used under the hood by the StencilView widget. It provides an efficient way to clip the drawing area of children. The StencilView class is defined in the “kivy.uix.stencilview” module. from kivy.uix.stencilview import StencilView It may be noted that StencilView is not a layout. Hence, to add widgets to StencilView, you have to combine a StencilView and a Layout in order to achieve a layout”s behavior. Further, you cannot add more than 128 stencil-aware widgets to the StencilView. The general usage of StencilView is as follows − st = StencilView(size=(x,y)) w = Widget() st.add_widget(w) To understand how exactly StencilView limits the drawable area of a widget, let us first execute certain graphics drawing instructions, and then impose StencilView to see the difference. Example In the following code, a mywidget class extends the Widget class, and draws 200 circles at random positions and with random RGB values. (This doesn”t use StencilView yet) from kivy.app import App from kivy.uix.widget import Widget from kivy.graphics import * import random from kivy.core.window import Window Window.size = (720, 350) class mywidget(Widget): def __init__(self, *args): super().__init__(*args) for i in range(200): colorR = random.randint(0, 255) colorG = random.randint(0, 255) colorB = random.randint(0, 255) posx = random.randint(0, Window.width) posy = random.randint(0, Window.height) self.canvas.add(Color(rgb=(colorR / 255.0, colorG / 255.0, colorB / 255.0))) d = 30 self.canvas.add(Ellipse(pos=(posx, posy), size=(d, d))) class circlesapp(App): def build(self): w = mywidget() return w circlesapp().run() Output As you can see, the circles are drawn at random positions all over the app window area. Now we chall apply the StencilView, and restrict the drawing area to 400×300 pixels in the center of the main window. The StencilView object is created and we add a Widget object to it. The drawing loop remains the same. class circlesapp(App): def build(self): st = StencilView( size_hint=(None, None), size=(400, 300), pos_hint={”center_x”:.5, ”center_y”:.5} ) w=widget() st.add_widget(w) return st If we now run the app, we should see the random circles appearing inside the stencil area, for all the positions outside it the drawing instructions are restricted. Print Page Previous Next Advertisements ”;