![]() |
|---|
| © dotmodus |
由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~
本文GitPage地址
Install
sudo add-apt-repository ppa:kivy-team/kivy-dailysudo apt-get updatesudo apt-get install python-kivy
sudo python3.7 -m pip install --upgrade pip wheel setuptools bcmsudo python3.7 -m pip install docutils pygmentssudo python3.7 -m pip install kivy.deps.gstreamer --extra-index-url https://kivy.org/downloads/packages/simple/
Quick Start

Kivy - Open source Python library for rapid development of applications that make use of innovative user interfaces, such as multi-touch apps.
## Creat a Hello.kv file in the path you run your scriptvim hello.kv### this is for Hello.kvBoxLayout:Label:text: "Hello"
##!/usr/bin/python3.6from kivy.app import Appclass HelloApp(App):passif __name__ == '__main__':HelloApp().run()
You need to name the kv file as hello.kv.
This file is target by the function HelloApp in main.py automatically.
Text layout
## hello.kv fileBoxLayout:Label:text: "Hello"Label:text: "Beautiful"Label:text: "World"

Button Layout
## hello.kv fileAddLocationForm:<AddLocationForm@BoxLayout>:orientation: "vertical"BoxLayout:TextInput:Button:text: "Search"size_hint_x: 1size_hint_y: 0.3Button:text: "Current Location"size_hint_x: 0.5

AddLocationForm:<AddLocationForm@BoxLayout>:orientation: "vertical"BoxLayout:height: "40dp"size_hint_y: NoneTextInput:size_hint_x: 50Button:text: "Search"size_hint_x: 25Button:text: "Current Location"size_hint_x: 25BoxLayout:Label:text: "Palo Alto, MX\nPalo Alto, US"


Events
Responding to Input
In this section, We’d like to acquire the input information from the input box.
For respond the Input message, two things we need to done:
- Assign an ID for TextInput
- line 5: Acquiring Input.
- line 10: Assign the ID “search_box” to TextInput Box
- line 15: active function search_location()
- Assign an function for responding the text
- line 5: import the function
- line 11-12: assigning the function to acquire and respond the massage from TextInput
Weather.kv:
AddLocationForm:<AddLocationForm@BoxLayout>:orientation: "vertical"search_input: search_box # Change oneBoxLayout:height: "40dp"size_hint_y: NoneTextInput:id: search_box # Assign an IDsize_hint_x: 50Button:text: "Search"size_hint_x: 25on_press: root.search_location()Button:text: "Current Location"size_hint_x: 25BoxLayout:Label:text: "Palo Alto, MX\nPalo Alto, US"
main.py:
##!/usr/local/bin/python3.7from kivy.app import Appfrom kivy.uix.boxlayout import BoxLayoutfrom kivy.properties import ObjectPropertyclass AddLocationForm(BoxLayout):search_input = ObjectProperty()def search_location(self):print("The user searched for '{}'".format(self.search_input.text))####class WeatherApp(App):passif __name__ == '__main__':WeatherApp().run()
Image left: GUI Layout; Image right: result was printed in terminal after clicked the button search.


In the current version Kivy1.11.1,
The function ListView is not is not supported.
Use Recycle As instead.
Take this as example:
from: https://stackoverflow.com/questions/56601384/kivy-unknown-class-listview-error-code
main.py
Light Weather App
from kivy.app import Appfrom kivy.uix.boxlayout import BoxLayoutfrom kivy.uix.recycleview.views import RecycleDataViewBehaviorfrom kivy.uix.label import Labelfrom kivy.properties import BooleanProperty, ObjectPropertyfrom kivy.uix.recycleboxlayout import RecycleBoxLayoutfrom kivy.uix.behaviors import FocusBehaviorfrom kivy.uix.recycleview.layout import LayoutSelectionBehaviorfrom kivy.network.urlrequest import UrlRequestfrom kivy.lang import Builderimport jsonclass SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior,RecycleBoxLayout):''' Adds selection and focus behaviour to the view. '''class SelectableLabel(RecycleDataViewBehavior, Label):''' Add selection support to the Label '''index = Noneselected = BooleanProperty(False)selectable = BooleanProperty(True)def refresh_view_attrs(self, rv, index, data):''' Catch and handle the view changes '''self.index = indexreturn super(SelectableLabel, self).refresh_view_attrs(rv, index, data)def on_touch_down(self, touch):''' Add selection on touch down '''if super(SelectableLabel, self).on_touch_down(touch):return Trueif self.collide_point(*touch.pos) and self.selectable:return self.parent.select_with_touch(self.index, touch)def apply_selection(self, rv, index, is_selected):''' Respond to the selection of items in the view. '''self.selected = is_selectedclass AddLocationForm(BoxLayout):search_input = ObjectProperty()search_results = ObjectProperty()def search_location(self):search_template = "https://samples.openweathermap.org/data/2.5/find?q={}&appid=b6907d289e10d714a6e88b30761fae22"# search_template = "https://api.openweathermap.org/data/2.5/find?q={}&typle=like&appid=xyz" # Replace 'xyz' with your API Key (APPID)search_url = search_template.format(self.search_input.text)request = UrlRequest(search_url, self.found_location)def found_location(self, request, data):data = json.loads(data.decode()) if not isinstance(data, dict) else datacities = ["{} ({})".format(d['name'], d['sys']['country']) for d in data['list']]self.search_results.data = [{'text': str(x)} for x in cities]print(f"self.search_results.data={self.search_results.data}")class WeatherRoot(BoxLayout):passclass TestApp(App):title = "Weather App"def build(self):return Builder.load_file("main.kv")if __name__ == '__main__':TestApp().run()
mian.kv
WeatherRoot:<WeatherRoot>:AddLocationForm:<SelectableLabel>:# Draw a background to indicate selectioncanvas.before:Color:rgba: (1, 0, 0, 1) if self.selected else (.0, 0.9, .1, .3)Rectangle:pos: self.possize: self.sizeColor:rgba: (0, 0.9, .1, .3)Rectangle:pos: self.possize: self.size<AddLocationForm>:orientation: "vertical"search_input: search_inputsearch_results: search_results_listBoxLayout:height: "40dp"size_hint_y:NoneTextInput:id: search_inputsize_hint_x: 50focus: Truemultiline: Falsehint_text: 'Your city name'on_text_validate: root.search_location()Button:text: "Search"size_hint_x: 25on_press: root.search_location()Button:text: "Current Location"size_hint_x: 25RecycleView:id: search_results_listviewclass: 'SelectableLabel'SelectableRecycleBoxLayout:default_size: None, dp(26)default_size_hint: 1, Nonesize_hint_y: Noneheight: self.minimum_heightorientation: 'vertical'multiselect: Truetouch_multiselect: True
Examples
UrlRequest
Origin from:coder.work
from kivy.app import App##kivy.require("1.9.1")from kivy.uix.boxlayout import BoxLayoutfrom kivy.properties import ObjectPropertyfrom kivy.network.urlrequest import UrlRequestclass MyWidget(BoxLayout):def __init__(self,**kwargs):super(MyWidget,self).__init__(**kwargs)search_url = "http://api.openweathermap.org/data/2.5/forecast/daily?APPID=ef4f6b76310abad083b96a45a6f547be&q=new%20york"print search_urlself.request = UrlRequest(search_url, self.res)print self.requestprint "Result: before success", self.request.result,"\n"def res(self,*args):print "Result: after success", self.request.resultclass MyApp(App):def build(self):return MyWidget()if __name__ == '__main__':MyApp().run()
Some Awesome Blogs
Build a Mobile Application With the Kivy Python Framework Mike Driscoll Nov 04, 2019
Enjoy~
由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~
本文GitPage地址
GitHub: Karobben
Blog:Karobben
BiliBili:史上最不正經的生物狗

