Kivy – UrlRequest ”; Previous Next The UrlRequest class in Kivy framework lets you make asynchronous requests on the web and get the result when the request is completed. Its functionality is same as the XHR object in JavaScript. The UrlRequest class is defined in the “kivy.network.urlrequest” module. The constructor needs only one mandatory argument named as “url”. The class inherits Thread class in Python”s threading module. The parameters of UrlRequest constructor are − url − string representing the complete url string to call. on_success − A Callback function to call when the result has been fetched. on_redirect − A Callback function to call if the server returns a Redirect. on_failure − A Callback function to call if the server returns a Client or Server Error. on_error − A Callback function to call if an error occurs. on_progress − A Callback function that will be called to report progression of the download. on_cancel − A Callback function to call if user requested to cancel the download operation via the .cancel() method. on_finish − An additional callback function to call if request is done. req_body − string representing data to be sent along with the request. If this parameter is included, a POST will be done. If not, GET request is sent. req_headers − dict, defaults to None Custom headers to add to the request. chunk_size − Size of each chunk to read, used only when on_progress callback has been set. timeout − An integer, if set, blocking operations will timeout after this many seconds. method − The HTTP method to use, defaults to ”GET” (or ”POST” if body is specified) decode − bool, defaults to True. If False, skip decoding of the response. debug − bool, defaults to False. auth − HTTPBasicAuth, defaults to None. If set, request will use basicauth to authenticate. The cancel() method of UrlRequest object cancels the current request and the callback on_cancel will be called. Example First, we design a user interface consisting of a spinner holding URLs of httpbin.org with variable parameters, two readonly textboxes – one displays the result of URL fetched and second, the JSON string of the response headers. In between, an Image widget is placed. It displays an image if the content_type is of image type. These widgets are placed ina vertical bo layout. The layout is built with the following kv language script. #:import json json BoxLayout: orientation: ”vertical” TextInput: id: ti hint_text: ”type url or select from dropdown” size_hint_y: None height: 48 multiline: False BoxLayout: size_hint_y: None height: 48 Spinner: id: spinner text: ”select” values: [ ”http://httpbin.org/ip”, ”http://httpbin.org/headers”, ”http://httpbin.org/delay/3”, ”https://httpbin.org/image/png”, ] on_text: ti.text = self.text Button: text: ”GET” on_press: app.fetch_content(ti.text) size_hint_x: None width: 50 TextInput: readonly: True text: app.result_text Image: source: app.result_image nocache: True TextInput readonly: True text: json.dumps(app.headers, indent=2) The Kivy App class code is as given below. It basically sends different HTTP requests to httpbin.org. httpbin.org is a simple HTTP Request & Response Service. The application stores the result of UrlRequest in three string variables and displays in the widgets. When a URL is selected from the dropdown and the GET button is pressed, it invokes the fetch_content() method and collects the responses. If the repose header contains a content_type with image, the Image widget loads the image. from kivy.lang import Builder from kivy.app import App from kivy.network.urlrequest import UrlRequest from kivy.properties import NumericProperty, StringProperty, DictProperty import json from kivy.core.window import Window Window.size = (720,400) class UrlExample(App): status = NumericProperty() result_text = StringProperty() result_image = StringProperty() headers = DictProperty() def build(self): pass def fetch_content(self, url): self.cleanup() UrlRequest( url, on_success=self.on_success, on_failure=self.on_failure, on_error=self.on_error ) def cleanup(self): self.result_text = ”” self.result_image = ”” self.status = 0 self.headers = {} def on_success(self, req, result): self.cleanup() headers = req.resp_headers content_type = headers.get(”content-type”, headers.get(”Content-Type”)) if content_type.startswith(”image/”): fn = ”tmpfile.{}”.format(content_type.split(”/”)[1]) with open(fn, ”wb”) as f: f.write(result) self.result_image = fn else: if isinstance(result, dict): self.result_text = json.dumps(result, indent=2) else: self.result_text = result self.status = req.resp_status self.headers = headers def on_failure(self, req, result): self.cleanup() self.result_text = result self.status = req.resp_status self.headers = req.resp_headers def on_error(self, req, result): self.cleanup() self.result_text = str(result) UrlExample().run() Output Run the above code. Select the ”http://httpbin.org/headers” from the spinner dropdown and press the GET button. You should see the response header in the text boxes. Choose ”https://httpbin.org/image/png” URL. The image will be displayed as shown. One of the options in the spinner dropdown is a URL pointing to the IPaddress of the client. Select ”http://httpbin.org/ip” from the list. The IP address will be displayed as shown below − Print Page Previous Next Advertisements ”;
Category: kivy
Kivy – Videos
Kivy – Videos ”; Previous Next The Video widget in Kivy framework capable of displaying video files and streams. The video formats you can play with Video widget depend on the operating system, video provider installed along with plugins required if any. The GStreamer provider is capable of handling almost any video codecs such as mpg, avi, mp4, mov, etc. The Video class is defined in the “kivy.uix.video” module. from kivy.uix.video import Video vid = Video(**args) The only mandatory parameter required to the constructor is the source property – a string representing the path to a video file. vid = Video(source = “test.mp4″) In order to start the video playback, you need to set its play property to True. You can pass this parameter in the constructor to start the video as soon as it is loaded, or set it to True/False as and when required. # start playing the video at creation video = Video(source=”test.mp4”, play=True) # create the video, and start later video = Video(source=”test.mp4”) # and later video.play = True Other properties of Video class are listed below − duration − Duration of the video. The duration defaults to “-1”, and is set to a real duration when the video is loaded. eos − Stands for “end of stream”. A Boolean property indicates whether the video has finished playing or not (reached the end of the stream). play − Indicates whether the video is playing or not. You can start/stop the video by setting this property to True or False. position − Position of the video between 0 and duration. The position defaults to -1 and is set to a real position when the video is loaded. seek() − Change the position to seek as a proportion of the total duration, must be between 0-1. state − A string, indicating whether to play, pause, or stop the video − # start playing the video at creation video = Video(source=”test.mp4”, state=”play”) # create the video, and start later video = Video(source=”test.mp4”) # and later video.state = ”play” volume − Volume of the video, in the range 0-1. 1 means full volume, 0 means mute. Example from kivy.app import App from kivy.uix.videoplayer import VideoPlayer from kivy.uix.video import Video from kivy.core.window import Window Window.size = (720,400) class MainApp(App): title = “Simple Video” def build(self): player = Video(source = “earth.mp4″, size_hint = (1,1), options={”fit_mode”: ”contain”}) player.state = ”play” player.options = {”eos”: ”loop”} player.allow_stretch=True return player MainApp().run() Output The video playback starts as you run the above code − Print Page Previous Next Advertisements ”;
Kivy – Packaging
Kivy – Packaging ”; Previous Next The term “packaging” refers to creating a single package of the source code of the application along with all the dependencies which includes the libraries, data files configuration files, etc. When you develop a Kivy app, it needs various resources. For example, the common requirement is sdl2 package, or glew package. When you install Kivy, these dependencies are also installed. kivy-deps.glew kivy-deps.gstreamer kivy-deps.sdl2 So far, you have been running the Kivy app from your machine which has Python runtime already installed. Hoewever, when it comes to porting this application to another machine that doesn”t have Python installed, you need to build a package which consists of the program along with the Python runtime as well as the dependencies. PyInstaller package helps you to build a redistributable package of your app. The user need not install Python, Kivy or any other library to run the app. To build such a distributable package, you should first install PyInstaller in your current Kivy environment with the PIP command. pip3 install -U pyinstaller The next step is to collect one or more Python source files (with .py extension), along with other resources such as image files etc. in a separate folder. For this exercise, we shall be building a package for ImageButton app. The files for this app are stored in imgbtn folder. Directory of C:kivyenvimgbtn forward.png main.py pause.png play.png previous.png Create another folder ImangBtnApp that will eventually store the distributable package. From within the folder, execute the following command − (kivyenv) C:kivyenvImageBtnApp>pyinstaller -n ImageBtnApp c:kivyenvimgbtnmain.py A Kivy app has a lot of dependencies. Hence, it might take a while to collect all of them. Eventually, the ImageButtonApp folder will populate with − Directory of C:kivyenvImageBtnApp 27-07-2023 21:25 <DIR> . 27-07-2023 21:07 <DIR> .. 27-07-2023 21:25 <DIR> build 27-07-2023 21:28 <DIR> dist 27-07-2023 21:25 970 ImageBtnApp.spec The dist folder is the distributable folder in which you will find the EXE file “ImageBtnApp.exe”, along with the DLL libraries required such as sdl2 etc. There is a spec file of the name of the app. we need to edit the spec file to add the dependencies hooks to correctly build the exe. Open the spec file with your favorite editor and add these lines at the beginning of the spec − from kivy_deps import sdl2, glew Scroll down the spec file to locate COLLECT section and add a Tree object for every path of the dependencies. E.g. *[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins)]. coll = COLLECT( exe, Tree(”c:\kivyenv\imgbtn\”), a.binaries, a.zipfiles, a.datas, *[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins)], strip=False, upx=True, upx_exclude=[], name=”ImageBtnApp”, ) Now we build the spec file in ImageBtnApp with − python -m PyInstaller ImageBtnApp.spec The compiled package will be in the ImageBtnAppdistImageBtnApp directory. You can also put the runtime, application code and the dependencies in a single file (instead of the distributable package) with -onetime switch of the Pyinstaller commandline syntax − pyinstaller –onefile -n ImageBtnApp To build a distributable package targeted for Android, you need to use Buildozer tool. It downloads and sets up all the prerequisites for pythonfor-android, including the android SDK and NDK, then builds an apk that can be automatically pushed to the device. Navigate to your project directory and run − buildozer init This creates a buildozer.spec file controlling your build configuration. Edit the file with your app name etc. You can set variables to control most or all of the parameters passed to python-for-android. Finally, plug in your android device and run − buildozer android debug deploy run to build, push and automatically run the APK on your device. Print Page Previous Next Advertisements ”;
Kivy – Utils
Kivy – Utils ”; Previous Next The “kivy.utils” module in Kivy library is a collection of general utility functions in various categories such as maths, color, algebraic function etc. QueryDict The object of QueryDict class is similar to Python”s built-in dict class. Additionally it has a provision to query the object with dot ( . ) operator. To construct QueryDict, you can either pass a list of two element tuples, or a dict object itself. # list of tuples qd = QueryDict([(”a”,1), (”b”,2)]) print (qd) Each tuple element of the list should have two items. First item is the key, and the second item is its value. {”a”: 1, ”b”: 2} On the other hand, you can pass a dict object itself to QueryDict constructor. qd=QueryDict({”a”:1, ”b”:2}) While the value belonging to a certain key can be fetched with the [] operator defined in the standard dict, the QueryDict provides a dot operator. Hence, “qd.k” is same as “qd[”k”]”. Note that the get() method od dict class can also be used with QueryDict. You can update the value of a key using the conventional slice operator assignment or the dot operator. qd.a=100 qd[”b”]=200 Try out the example below − from kivy.utils import * # list of tuples qd=QueryDict([(”a”,1), (”b”,2)]) print (qd) print (qd.a, qd[”a”]) qd=QueryDict({”a”:1, ”b”:2}) print (qd) print (qd.b, qd[”b”]) print (qd.get(”a”)) qd.a=100 qd[”b”]=200 print (qd) SafeList The SafeList class in Kivy inherits the built-in list class. In addition to the methods inherited from list, a new method − clear() is defined in SafeList class. It removes all items in the list. You can pass a mutable sequence (list) to the constructor to create a SafeList object. If no argument is passed, it creates an empty list. Calling clear() method removes all items. Example from kivy.utils import * sl = SafeList([1,2,3,4]) print (“SafeList:”,sl) l = [1,2,3,4] sl = SafeList(l) print (“SafeList:”,sl) sl.clear() print (“SafeList:”,sl) Output SafeList: [1, 2, 3, 4] SafeList: [1, 2, 3, 4] SafeList: [] difference() This function returns the difference between two lists. More specifically, it removes those items from the first list that are found in the second list. Example from kivy.utils import * l1=[1,2,3,4] l2=[3,4,5,6] print (l1, l2) print (“l1-l2:”,difference(l1,l2)) print (“l2-l1:”,difference(l2,l1)) Output [1, 2, 3, 4] [3, 4, 5, 6] l1-l2: [1, 2] l2-l1: [5, 6] escape_markup() A Label on Kivy app window is capable of displaying a markup text. However, if you want effect of the markup symbols not to take effect, you can escape markup characters found in the text. This is intended to be used when markup text is activated on the Label. In the example below, the text to be displayed on the label contains [b] and [/b] markup tags, which would convert the test to bold. However, to ignore this effect, the text is passed to escape_markup() function. Example from kivy.app import App from kivy.uix.label import Label from kivy.utils import escape_markup from kivy.core.window import Window Window.size = (720,400) class HelloApp(App): def build(self): text = ”This is an [b]important[/b] message” text = ”[color=ff0000]” + escape_markup(text) + ”[/color]” lbl=Label(text=text, font_size=40, markup=True) return lbl HelloApp().run() Output get_color_from_hex() Transform a hex string color to a kivy Color. The RGBA values for color property are given to be between 0 to 1. Since RGB values range from 0 to 255, the Kivy Color values divide the number by 255. Hence RGB values 50, 100, 200 are represented as 50/255, 100/255 and 200/255 respectively. The hex color values are given as a string with 2 hexadecimal numbers each for RGB and prefixed by the “#” symbol. The get_color_from_hex() function converts a Hex string to Kivy color values. Example from kivy.utils import * c = get_color_from_hex(“#00ff00”) print (c) Output [0.0, 1.0, 0.0, 1.0] get_hex_from_color(color) Transform a kivy Color to a hex value − Example from kivy.utils import * c = get_hex_from_color([0,1,0,1]) print (c) Output #00ff00ff rgba() returns a Kivy color (4 value from 0-1 range) from either a hex string or a list of 0-255 values. Example from kivy.utils import * # from RGBA color values c = rgba([100,150,200, 255]) print (“from RGBA:”,c) # from hex string c = rgba(”#3fc4e57f”) print (“from hex string:”,c) Output from RGBA: [0.39215686274509803, 0.5882352941176471, 0.7843137254901961, 1.0] from hex string: [0.24705882352941178, 0.7686274509803922, 0.8980392156862745, 0.4980392156862745] Print Page Previous Next Advertisements ”;
Kivy – Color Picker
Kivy – Color Picker ”; Previous Next Kivy”s ColorPicker widget is an inbuilt dialog box that lets you choose a color in more than one ways. It provides a chromatic color wheel from which to choose the required color. It also has slider controls, which can adjust to get the desired color value. Sliders are also available for transparency and color values in HSV scheme. Each of these color attributes have a text box in which you can directly enter a numeric color value ranging between 0 and 255. The ColorPicker widget appears like this − The ColorPicker class is defined in the “kivy.uix.colorpicker” module. from kivy.uix.colorpicker import ColorPicker colour = ColorPicker(**kwargs) To render the above color dialog, just add the ColorPicker object to the parent window. If its color property is bound to an event handler, the color value can be used for further processing like changing the color of a certain object with the chosen color. In addition to color, the ColorPicker object has hsv and hex_color properties. In the following snippet, the color, hsv and hex_color values are printed on the console when a color is chosen. For a color selected from the wheel, the RGB, HSV, A and hex values are displayed in the text boxes as well as indicated by the slider positions. The callback method prints the values on the console − RGBA = [1, 0.5, 0.5, 1] HSV = (0.0, 0.5, 1) HEX = #ff7f7fff ColorPicker Properties r − The Red value of the color currently selected. It is a BoundedNumericProperty and can be a value from 0 to 1. It defaults to 0. g − The Green value of the color currently selected. “g” is a BoundedNumericProperty and can be a value from 0 to 1. b − The Blue value of the color currently selected. “b” is a BoundedNumericProperty and can be a value from 0 to 1. a − The Alpha value of the color currently selected. “a” is a BoundedNumericProperty and can be a value from 0 to 1. hsv − The hsv holds the color currently selected in hsv format. hsv is a ListProperty and defaults to (1, 1, 1). hex_color − The hex_color holds the currently selected color in hex. hex_color is an AliasProperty and defaults to #ffffffff. color − The color holds the color currently selected in rgba format. color is a ListProperty and defaults to (1, 1, 1, 1). font_name − Specifies the font used on the ColorPicker. font_name is a StringProperty. wheel − The wheel holds the color wheel. wheel is an ObjectProperty and defaults to None. Example Let us the ColorPicker widget to select any desired color, either from the wheel or from the sliders, or by directly entering the color values; and apply it to the label on the parent window. The Kivy application window contains a label and a button placed in a grid layout. On the on_press event of the button a popup is displayed. The popup is designed with a ColorPicker and a button in another grid layout. The popup button applies the chosen color to the label on application window before dismissing the popup. from kivy.app import App from kivy.uix.button import Button from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout from kivy.uix.popup import Popup from kivy.uix.colorpicker import ColorPicker from kivy.core.window import Window Window.size = (720, 350) class ColorPickApp(App): def build(self): self.layout = GridLayout(cols=1, padding=10) self.l1 = Label( text=”www.tutorialspoint.com”, 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) self.clr = ColorPicker() closeButton = Button(text=”OK”, size_hint=(.1, .05)) layout.add_widget(self.clr) layout.add_widget(closeButton) self.popup = Popup( title=”Hello”, content=layout, auto_dismiss=False ) self.popup.open() closeButton.bind(on_press=self.on_close) def on_close(self, event): self.l1.color = self.clr.hex_color self.popup.dismiss() ColorPickApp().run() Output The initial display of this Kivy app would show a label and a button. When you click the button, the ColorPicker widget will popup. Select the desired color and press OK. You will see the Label text changing its color accordingy. Print Page Previous Next Advertisements ”;
Kivy – Multistroke
Kivy – Multistroke ”; Previous Next A MultiStroke Gesture in Kivy is a set of more than one Gesture objects. A Gesture constitutes a single stroke constructed out of a list of touch points between the “touch_down” and “touch_up” events. A MultiStrokeGesture is a collection of such strokes. The “kivy.multistroke” module implements the Protractor gesture recognition algorithm. The two important classes defined in this module are MultistrokeGesture and Recognizer. The MultiStrokeGesture class maintains a set of strokes and generates unistroke (i.e., UnistrokeTemplate) permutations that are used for evaluating candidates against this gesture later. A MultriStroke object is obtained with the help of the following syntax − from kivy.vector import Vector from kivy.multistroke import MultistrokeGesture gesture = MultistrokeGesture(”my_gesture”, strokes=[ [Vector(x1, y1), Vector(x2, y2), …… ], # stroke 1 [Vector(), Vector(), Vector(), Vector() ] # stroke 2 #, [stroke 3], [stroke 4], … ]) Even though all the strokes are combined to a single list (unistroke), you should still specify the strokes individually, and set stroke_sensitive property to True. Recognizer stores the list of MultistrokeGesture objects. It is the search/database API similar to GestureDatabase. It maintains a list of and allows you to search for a user-input gestures among them. The Recognizer database is a a container for UnistrokeTemplate objects, and implements the heap permute algorithm to automatically generate all possible stroke orders. An object of Candidate class represents a set of unistroke paths of user input. This object instantiated automatically by calling Recognizer.recognize(). from kivy.vector import Vector from kivy.multistroke import Recognizer gdb = Recognizer() gdb.recognize([ [Vector(x1, y1), Vector(x2, y2)], [Vector(x3, y3), Vector(x4, y4)]]) The Recognizer object is able to generate these events − on_search_start − Fired when a new search is started using this Recognizer. on_search_complete − Fired when a running search ends, for whatever reason. These events can be mapped to callbacks to track the progress of search operation done by the Recognizer.recognize() method. gdb.bind(on_search_start=search_start) gdb.bind(on_search_complete=search_stop) The examples of callback methods are as follows − def search_start(gdb, pt): print(“A search is starting with {} tasks”.format(pt.tasks)) def search_stop(gdb, pt): best = pt.best print(“Search ended {}. Best is {} (score {}, distance {})”.format( pt.status, best[”name”], best[”score”], best[”dist”] )) Lastly, the “kivy.multistroke” module also provides a ProgressTracker class. It represents an ongoing (or completed) search operation. The tracker object is instantiated automatically and returned by the Recognizer.recognize() method when it is called. The results attribute is a dictionary that is updated as the recognition operation progresses. progress = gdb.recognize([ [Vector(x1, y1), Vector(x2, y2)], [Vector(x3, y3), Vector(x4, y4)]]) progress.bind(on_progress=my_other_callback) print(progress.progress) # = 0 print(result.progress) # = 1 You can save the multistroke gestures to a file with export_gesture() function. export_gesture(filename=None) − It exports a list of MultistrokeGesture objects to a base64-encoded string that can be decoded to a Python list with the parse_gesture() function. It can also be imported directly to the database using Recognizer.import_gesture(). If filename is specified, the output is written to disk. import_gesture(data=None,filename=None) − The import_gesture() function brings the gesture in a Recognizer database. Use this function to import a list of gestures as formatted by export_gesture(). Either data or filename parameter must be specified. This method accepts optional Recognizer.filter() arguments, if none are specified then all gestures in specified data are imported. Print Page Previous Next Advertisements ”;
Kivy – Toggle Button
Kivy – Toggle Button ”; Previous Next The ToggleButton widget in the Kivy framework behaves somewhat like a Checkbox widget. It also has a binary property called state which has two possible values − normal or down. The ToggleButton is a button with the difference that when a button is pressed, the pressed and released events occur almost simultaneously; whereas when a toggle button is pressed, the down state persists till it is again pressed to bring to normal state. The two states of a ToggleButton have a distinct background color for each state, which may be customized by assigning value to “background_normal” and “background_down” properties. The ToggleButton class inherits Button class and the ToggleButtonBehavior mixin. It is defined in kivy.uix.togglebutton module from kivy.uix.togglebutton import ToggleButton toggle = ToggleButton(**kwargs) Just like the Checkbox, multiple ToggleButton objects can be grouped together. By default, each toggle button can be used to represent two states (such as ON/OFF in Switch widget). But, if multiple toggle buttons have the same value for group property, only one in the group will have down state. When one of the grouped buttons is down, the rest will be automatically set to normal. btn1 = ToggleButton(text=”Male”, group=”sex”,) btn2 = ToggleButton(text=”Female”, group=”sex”, state=”down”) In this case, the two buttons belong to the same group, and hence only one of them can be in down state at a time. Since it inherits Button class, we can process the on_press event on a toggle button. Additionally, the “on_state” event can be bound to its state property. Example 1 The following code puts three Toggle Buttons that are not grouped. Hence, each of them can be put to normal or down state. In the example below, these toggle buttons represent the subjects of interest to be chosen by the user. self.button1 = ToggleButton(text =”Sports”, font_size=32) self.button2 = ToggleButton(text=”Music”, font_size=32) self.button3 = ToggleButton(text=”Travel”, font_size=32) They are bound to callbacks to identify the state of each button self.button1.bind(on_press=self.btn1pressed) self.button2.bind(on_press=self.btn2pressed) self.button3.bind(on_press=self.btn3pressed) Each callback method checks if the state is down, and accordingly updates the label text. def btn1pressed(self, instance): if instance.state==”down”: self.sports=”Sports” else: self.sports=”” self.l1.text=”{} {} {}”.format(self.sports, self.music, self.travel) The complete code for this exercise is given below − from kivy.app import App from kivy.uix.togglebutton import ToggleButton from kivy.uix.label import Label from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.core.window import Window Window.size = (720, 350) class toggledemoapp(App): def build(self): self.sports = self.music = self.travel = ”” layout = GridLayout(cols=1, padding=10) box = BoxLayout(orientation=”horizontal”) lbl = Label(text=”My Interests”, font_size=40) layout.add_widget(lbl) self.l1 = Label( text=”Choose One or More”, font_size=32, color=[.8, .6, .4, 1] ) layout.add_widget(self.l1) self.button1 = ToggleButton(text=”Sports”, font_size=32) self.button2 = ToggleButton(text=”Music”, font_size=32) self.button3 = ToggleButton(text=”Travel”, font_size=32) self.button1.bind(on_press=self.btn1pressed) self.button2.bind(on_press=self.btn2pressed) self.button3.bind(on_press=self.btn3pressed) box.add_widget(self.button1) box.add_widget(self.button2) box.add_widget(self.button3) layout.add_widget(box) return layout def btn1pressed(self, instance): if instance.state == ”down”: self.sports = ”Sports” else: self.sports = ”” self.l1.text = “{} {} {}”.format(self.sports, self.music, self.travel) def btn2pressed(self, instance): if instance.state == ”down”: self.music = ”Music” else: self.music = ”” self.l1.text = “{} {} {}”.format(self.sports, self.music, self.travel) def btn3pressed(self, instance): if instance.state == ”down”: self.travel = ”Travel” else: self.travel = ”” self.l1.text = “{} {} {}”.format(self.sports, self.music, self.travel) toggledemoapp().run() Output The application opens with all the buttons in normal state. Try and put any of them in “down”. Example 2 The following example assembles the labels and toggle buttons in similar layout as the above image shows, except that the toggle buttons are now grouped together. We shall use a “kv” script to design the app layout. The Mylayout class is used as the root of the app, and uses GridLayout as its base. class Mylayout(GridLayout): def callback(self, *args): print (args[0].text) self.ids.l1.text=args[0].text class togglegroupapp(App): def build(self): return Mylayout() togglegroupapp().run() Here is the “kv” language script. It puts three toggle buttons in a horizontal box, which in tur is a part of the one-column grid layout. All the buttons have same value ”branch” of group property, and are bound to the callback() method of MyLayout class above. The callback() method puts the caption of the button that caused the on_press event, on the label to show which branch has the user chosen. <Mylayout>: size: root.width, root.height cols:1 Label: text:”Which is your Engineering branch?” font_size:40 Label: id:l1 text: ”Choose Any One” font_size:32 color:[.8,.6,.4,1] BoxLayout: orientation:”horizontal” ToggleButton: text : “Electronics” font_size : 32 group:”branch” on_press:root.callback(*args) ToggleButton: text:”Mechanical” font_size:32 group:”branch” on_press:root.callback(*args) ToggleButton: text:”Comp.Sci” font_size:32 group:”branch” on_press:root.callback(*args) Output Run the program and experiment with the button states as shown below − Print Page Previous Next Advertisements ”;
Kivy – Video Player
Kivy – Video Player ”; Previous Next The VideoPlayer widget in Kivy library is a ready to use control to play a video file and control its playback and sound. It is a predefined layout with the playing area and buttons to play/stop and pause/resume playback. It also has a seekbar with which the play position can be moved to a desired place. The VideoPlayer class is defined in the “kivy.uix.videoplayer” module. from kivy.uix.videoplayer import VideoPlayer player = VideoPlayer(**kwargs) You need to assign the source property of a VideoPlayer object with a String representing the video file to be played. Kivy supports different video formats including “mp4”, “avi” and “mpg”. To start the video, you should set the state property to ”play” from kivy.uix.videoplayer import VideoPlayer player = VideoPlayer(source = “test.mp4″) player.state = ”play” One of the important features of Kivy”s VideoPlayer is its ability to display text annotations at specific position in the video and for a certain duration. The annotations are provided in a file with “.jsa” extension, and with the same name as that of the video file. The .jsa file is a JSON based file format. It contains the values for start position of the annotation, the duration in seconds for which it is displayed on the screen, and the annotation text. [ {“start”: 0, “duration”: 2, “text”: “Introduction”}, {“start”: 10, “duration”: 5, “text”: “Hello World”}, ] To keep the video playing in a loop, set the eos option to loop − options={”eos”: ”loop”} The VideoPlayer class defines the following properties − source − The source of the video to read. source is a StringProperty representing the path of the video file to be played state − A string, indicates whether to play, pause, or stop the video. state is an OptionProperty and defaults to ”stop”. allow_fullscreen − By default, you can double-tap on the video to make it fullscreen. Set this property to False to prevent this behavior. position − Position of the video between 0 and duration. The position defaults to -1 and is set to the real position when the video is loaded. seek(percent, precise=True) − Change the position to a percentage (strictly, a proportion) of duration. The percent value should be a float or int and between 0-1. The precise parameter is a bool, defaults to True where precise seeking is slower, but seeks to exact requested percent. thumbnail − Thumbnail of the video to show. If None, VideoPlayer will try to find the thumbnail from the source + ”.png”. volume − Volume of the video in the range 0-1. 1 means full volume and 0 means mute. annotation − The VideoPlayer uses a VideoPlayerAnnotation object to construct annotations, based on the JSON data stored in a JSA file. Following keys are allowed to be used in JSA file − start − The position at which the annotation is to be displayed duration − Time for which the annotation label is displayed on the player window. text − The text to be displayed as annotation. bgcolor − [r, g, b, a] – background color of the text box bgsource − ”filename” – background image used for the background text box border − (n, e, s, w) – border used for the background image Example Th following code renders a video player widget on the application window − from kivy.app import App from kivy.uix.videoplayer import VideoPlayer from kivy.core.window import Window Window.size = (720, 350) class MainApp(App): title = “Simple Video” def build(self): player = VideoPlayer( source=”video.mp4″, size_hint=(0.8, 0.8), options={”fit_mode”: ”contain”} ) player.state = ”play” player.options = {”eos”: ”loop”} player.allow_stretch = True return player MainApp().run() Output Run the code and check the output − Print Page Previous Next Advertisements ”;
Kivy – Cache Manager
Kivy – Cache Manager ”; Previous Next In Kivy framework, the Cache class stores one or more Python objects by assigning them as value of a unique key. Kivy”s Cache manager controls the objects in it by either imposing a limit to the number of objects in it, or keeping a timeout limit to their access. The Cache class is defined in the “kivy.cache” module. It includes the static methods: register(), append(), get(), etc. To start with, you need to register a Category in the Cache manager by setting the maximum number of objects and the timeout. from kivy.cache import Cache Cache.register(category=”mycache”, limit=10, timeout=5) You can now add upto 10 Python objects, each with a unique key. key = ”objectid” instance = Label(text=text) Cache.append(”mycache”, key, instance) The get() method retrieves an object from the cache. instance = Cache.get(”mycache”, key) The Cache class defines the following methods and properties − register() Method This method registers a new category in the cache with the specified limit. It has the following parameters − category − A string identifier of the category. limit − Maximum number of objects allowed in the cache. If None, no limit is applied. timeout − Time after which the object will be removed from cache. append() Method This method add a new object to the cache. Following parameters are defined − category − string identifier of the category. key − Unique identifier of the object to store. obj − Object to store in cache. timeout − Time after which to object will be deleted if it has not been used. This raises ValueError if None is used as key. get() Method This method is used to get a object from the cache, with the following parameters − category − string identifier of the category.. key − Unique identifier of the object in the store.. default − Default value to be returned if the key is not found. Example Take a look at the following example − from kivy.cache import Cache from kivy.uix.button import Button from kivy.uix.label import Label Cache.register(category=”CacheTest”, limit=5, timeout=15) b1 = Button(text=”Button Cache Test”) Cache.append(category=”CacheTest”, key=”Button”, obj=b1) l1 = Label(text=”Label Cache Test”) Cache.append(category=”CacheTest”, key=”Label”, obj=l1) ret = (Cache.get(”CacheTest”, ”Label”).text) print (ret) Output It will produce the following output − Label Cache Test Print Page Previous Next Advertisements ”;
Kivy – Spinner
Kivy – Spinner ”; Previous Next The Spinner control in Kivy framework is a more conventional type of dropdown control, different from Kivy”s DropDown widget. Compared to DropDown, it is easier and convenient to construct and use the Spinner widget. The main difference between Kivy”s dropdown and spinner widgets is that the dropdown widget may consist of any other Kivy widget such as Label, Button, Image etc; while a spinner is simply a list of strings. The Spinner class is defined in the “kivy.uix.spinner” module from kivy.uix.spinner import Spinner spin = Spinner(**kwargs) A Spinner widget shows a text caption corresponding to the currently selected value. The Spinner object can be constructed with different properties as keyword arguments. However, these two properties are important − The text property is a string and shows the default value. The values property is a ListProperty, consisting of all the values to choose from. To construct a simple spinner, use the following code snippet − from kivy.base import runTouchApp from kivy.uix.spinner import Spinner spinner = Spinner( text=”English”, values=(”English”, ”French”, ”German”, ”Chinese”) ) The spinner object”s text property can be bound to a callback to invoke appropriate action whenever the selection is made. def value_changed(spinner, text): print(You selected”, text, ”language”) spinner.bind(text=show_selected_value) Other properties in the Spinner class are listed below − dropdown_cls − A class used to display the dropdown list when the Spinner is pressed. It is an ObjectProperty and defaults to DropDown. is_open − By default, the spinner is not open. Set to True to open it. option_cls − A class used to display the options within the dropdown list displayed under the Spinner. The text property of the class will be used to represent the value. Its on_release event is used to trigger the option when pressed/touched. text_autoupdate − This is BooleanProperty. It indicates if the spinner”s text should be automatically updated with the first value of the values property. Setting it to True will cause the spinner to update its text property every time values are changed. values − Values that can be selected by the user. It must be a list of strings. It is a ListProperty and defaults to []. The code below assembles a Spinner, associated with a label to show the selected value in the horizontal box. The lower horizontal box has a TextInput and a Button. The intention is to provide a callback on this button that adds the string in the textbox to the Spinner values The program has two callback methods in the App class. One to display the selected value from the spinner, and another to add a new language to the spinner. The callback to add a new language − def addvalue(self, instance): self.spin1.values.append(self.t1.text) We shall bind this method to the “Add” button. To display the selected language on a label − def on_spinner_select(self, spinner, text): self.spinnerSelection.text = “Selected Language is: %s” %self.spin1.text We shall bind this method to the “text” property of the Spinner widget. Example Save and run the code below as “spiinerdemo.py” from kivy.app import App from kivy.uix.label import Label from kivy.uix.spinner import Spinner from kivy.uix.boxlayout import BoxLayout from kivy.uix.textinput import TextInput from kivy.uix.button import Button from kivy.core.window import Window Window.size = (720, 400) class SpinnerExample(App): def addvalue(self, instance): self.spin1.values.append(self.t1.text) def build(self): layout = BoxLayout(orientation=”vertical”) lo1 = BoxLayout(orientation=”horizontal”) self.spin1 = Spinner( text=”Python”, values=(“Python”, “Java”, “C++”, “C”, “C#”, “PHP”), background_color=(0.784, 0.443, 0.216, 1), size_hint=(.5, .4), pos_hint={”top”: 1} ) lo1.add_widget(self.spin1) self.spinnerSelection = Label( text=”Selected value in spinner is: %s” % self.spin1.text, pos_hint={”top”: 1, ”x”: .4} ) lo1.add_widget(self.spinnerSelection) layout.add_widget(lo1) lo2 = BoxLayout(orientation=”horizontal”) lo2.add_widget(Label(text=”Add Language”)) self.t1 = TextInput() self.b1 = Button(text=”add”) lo2.add_widget(self.t1) lo2.add_widget(self.b1) layout.add_widget(lo2) self.spin1.bind(text=self.on_spinner_select) self.b1.bind(on_press=self.addvalue) return layout def on_spinner_select(self, spinner, text): self.spinnerSelection.text = “Selected value in spinner is: %s” % self.spin1.text print(”The spinner”, spinner, ”have text”, text) if __name__ == ”__main__”: SpinnerExample().run() Output The button on the top-left is the Spinner. When clicked, the list of languages drops down. You can make a selection. The selected name will be displayed on the label to its right. To add a new language to the list, type in the text box, and click the “Add” button. The spinner widget will be appended with the new language name at the bottom. If the list is long enough, you can scroll down with mouse. Print Page Previous Next Advertisements ”;