版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
1、QuickstartThis page explains how to create a simple Kivy “Hello world” program. This assumes you already have Kivy installed. If you do not, head over to the Installation section. We also assume basic Python 2.x knowledge throughout the rest of this documentation.Create an applicationThe base code f
2、or creating an application looks like this:import kivykivy.require('1.0.6') # replace with your current kivy version !from kivy.app import Appfrom import Buttonclass MyApp(App): def build(self): return Button(text='Hello World')if _name_ = '_main_': MyApp().run()Save it as ma
3、in.py.To run the application, follow the instructions for your operating system:LinuxFollow the instructions for running Kivy application on Linux:$ python main.pyWindowsFollow the instructions for running Kivy application on Windows:$ python main.py# orC:appdir>kivy.bat main.pyMac OS XFollow the
4、 instructions for running Kivy application on MacOSX:$ kivy main.pyAndroidYour application needs some complementary files to be able to run on Android. See Kivy on Android for further reference.A window should open, showing a sole button (with the label Hello World) that covers the entire windows ar
5、ea. Thats all there is to it.So what does that code do?1 First, we import Kivy, and check if the current installed version will be enough for our application. If not, an exception will be automatically fired, and prevent your application to crash in runtime. You can read the documentation of kivy.re
6、quire() function for more information.2 We import the App class, to be able to subclass it. By subclassing this class, your own class gains several features that we already developed for you to make sure it will be recognized by Kivy.3 Next, we import the Button class, to be able to create an instan
7、ce of a button with a custom label.4 Then, we create our application class, based on the App class. We extend the build() function to be able to return an instance of Button. This instance will be used as the root of the widget tree (because we returned it).5 Finally, we call run() on our applicatio
8、n instance to launch the Kivy process with our application inside.How to read the documentationThe documentation is seperated in 2 parts:· the Programming Guide: its a must read to understand the Kivy basics, specially if you never done GUI programming before.· the API: all the functions,
9、classes, methods are explained.Importing a classThe API part is autogenerated from the source code. If you take any class, it will be generated like this:It should be read like this: the “Button” class is into the “” module. So if you want to import that class in your code, write that:from import Bu
10、ttonControling the environmentMany environment variables are available to control the initialization and behavior of Kivy.For example, for restricting text rendering to PIL implementation:$ KIVY_TEXT=pil python main.pyEnvironment variable can be set before importing kivy:import osos.environ'KIVY
11、_TEXT' = 'pil'import kivyConfigurationKIVY_USE_DEFAULTCONFIGIf this name is found in environ, Kivy will not read the user config file.KIVY_NO_CONFIGIf set, no configuration file will be read or write, and no user configuration directory too.KIVY_NO_FILELOGIf set, logs will be not print o
12、n a fileKIVY_NO_CONSOLELOGIf set, logs will be not print on the consoleKIVY_DPIIf set, the value will be used instead of the value returned by the window.New in version 1.4.0.Path controlNew in version 1.0.7.You can control where is located default directory of modules, extensions, and kivy datas.KI
13、VY_DATA_DIRLocation of the Kivy data, default to <kivy path>/dataKIVY_EXTS_DIRLocation of the Kivy extensions, default to <kivy path>/extensionsKIVY_MODULES_DIRLocation of the Kivy modules, default to <kivy path>/modulesRestrict core to specific implementationkivy.core try to selec
14、t the best implementation available for your platform. For testing or custom installation, you might want to restrict the selector to a specific implementation.KIVY_WINDOWImplementation to use for creating the WindowValues: pygameKIVY_TEXTImplementation to use for rendering textValues: pil, pygameKI
15、VY_VIDEOImplementation to use for rendering videoValues: gstreamer, pyglet, ffmpegKIVY_AUDIOImplementation to use for playing audioValues: gstreamer, pygameKIVY_IMAGEImplementation to use for reading imageValues: pil, pygameKIVY_CAMERAImplementation to use for reading cameraValues: gstreamer, opencv
16、, videocaptureKIVY_SPELLINGImplementation to use for spellingValues: enchant, osxappkitKIVY_CLIPBOARDImplementation to use for clipboard managementValues: pygame, dummyConfigure KivyThe configuration file of kivy is named config.ini, following the INI format file.Locating the configuration fileThe l
17、ocation of the configuration file is in:<HOME_DIRECTORY>/.kivy/config.iniIf your user is named “tito”, the file will be located at:· Windows: C:Userstito.kivyconfig.ini· MacOSX: /Users/tito/.kivy/config.ini· Linux: /home/tito/.kivy/config.iniUnderstanding config tokensAll the co
18、nfiguration tokens are explained in the kivy.config module.Architectural OverviewWe would like to take a moment to explain how we designed Kivy from a software engineering point of view. This is key to understanding how everything works together. If you just look at the code, chances are you will ge
19、t a rough idea already, but since this approach certainly is daunting for most users, this section explains the basic ideas of the implementation in more detail. You can skip this section and refer to it later, but we suggest at least skimming it for a rough overview.Kivy consists of several buildin
20、g blocks that we will explain in the following.Core Providers and Input ProvidersOne idea that is key to understanding Kivys internals is that of modularity and abstraction. We try to abstract from basic tasks such as opening a window, displaying images and text, playing audio, getting images from a
21、 camera, spelling correction and so on. We call these core tasks. This makes the API both easy to use and easy to extend. Most importantly, it allows us to use what we call specific providers for the respective scenario in which your app is being run. For example, on OSX, Linux and Windows, there ar
22、e different native APIs for the different core tasks. A piece of code that uses one of these specific APIs to talk to the operating system on one side and to Kivy on the other (acting as an intermediate communication layer) is what we call a core provider. The advantage of using specialized core pro
23、viders for each platform is that we can fully leverage the functionality exposed by the operating system and act as efficiently as possible. It also gives users a choice. Furthermore, by using libraries that are shipped with any one platform, we effectively reduce the size of the Kivy distribution a
24、nd make packaging easier. Its also easier to port Kivy to other platforms. The Android port did greatly benefit from this.We follow the same concept with input handling. An input provider is a piece of code that adds support for a specific input device, such as Apples trackpads, TUIO or a mouse emul
25、ator. If you need to add support for a new input device, you can simply provide a new class that reads your input data from your device and transforms them into Kivy basic events.GraphicsKivys graphics API is our abstraction of OpenGL. On the lowest level, Kivy issues hardware-accelerated drawing co
26、mmands using OpenGL. Writing OpenGL code however can be a bit confusing, especially to newcomers. Thats why we provide the graphics API that lets you draw things using simple metaphors that do not exist as such in OpenGL (e.g. Canvas, Rectangle, etc.).All of our widgets themselves use this graphics
27、API, which is implemented on the C level for performance reasons.Another advantage of the graphics API is its ability to automatically optimize the drawing commands that your code issues. This is especially helpful if youre not an expert at tuning OpenGL. This makes your drawing code more efficient
28、in many cases.You can, of course, still use raw OpenGL commands if you prefer that. The version we target is OpenGL 2.0 ES (GLES2) on all devices, so if you want to stay cross-platform compatible, we advise you to only use the GLES2 functions.CoreThe code in the core package provides commonly used f
29、eatures, such as:ClockYou can use the clock to schedule timer events. Both one-shot timers and periodic timers are supportedCacheIf you need to cache something that you use often, you can use our class for that instead of writing your own.Gesture DetectionWe ship a simple gesture recognizer that you
30、 can use to detect various kinds of strokes, such as circles or rectangles. You can train it to detect your own strokes.Kivy LanguageThe kivy language is used to easily and efficiently describe user interfaces.PropertiesThese are not the normal properties that you may know from python. It is our own
31、 properties class that links your widget code with the user interface description.UIX (Widgets & Layouts)The UIX module contains commonly used widgets and layouts that you can reuse to quickly create a user interface.WidgetsWidgets are user interface elements that you add to your program to prov
32、ide some kind of functionality. They may or may not be visible. Examples would be a file browser, buttons, sliders, lists and so on. Widgets receive MotionEvents.LayoutsYou use layouts to arrange widgets. It is of course possible to calculate your widgets positions yourself, but often it is more con
33、venient to use one of our ready made layouts. Examples would be Grid Layouts or Box Layouts. You can also nest layouts.ModulesIf youve ever used a modern web browser and customized it with some add-ons then you already know the basic idea behind our module classes. Modules can be used to inject func
34、tionality into Kivy programs, even if the original author did not include it.An example would be a module that always shows the FPS of the current application and some graph depicting the FPS over time.You can also write your own modules.Input Events (Touches)Kivy abstracts from different input type
35、s and sources such as touches, mice, TUIO or similar. What all of these input types have in common is that you can associate a 2D onscreen-position with any individual input event. (There are other input devices such as accelerometers where you cannot easily find a 2D position for e.g. a tilt of you
36、r device. This kind of input is handled separately. In the following we describe the former types.)All of these input types are represented by instances of the Touch() class. (Note that this does not only refer to finger touches, but all the other input types as well. We just called it Touch for the
37、 sake of simplicity. Think of it of something that touches the user interface or your screen.) A touch instance, or object, can be in one of three states. When a touch enters one of these states, your program is informed that the event occurred. The three states a touch can be in are:DownA touch is
38、down only once, at the very moment where it first appears.MoveA touch can be in this state for a potentially unlimited time. A touch does not have to be in this state during its lifetime. A Move happens whenever the 2D position of a touch changes.UpA touch goes up at most once, or never. In practice
39、 you will almost always receive an up event because nobody is going to hold a finger on the screen for all eternity, but it is not guaranteed. If you know the input sources your users will be using, you will know whether or not you can rely on this state being entered.Widgets and Event DispatchingTh
40、e term widget is often used in GUI programming contexts to describe some part of the program that the user interacts with. For Kivy, a widget is an object that receives input events. It does not necessarily have to have a visible representation on the screen. All widgets are arranged in a widget tre
41、e (which is a tree data structure as known from computer science classes): One widget can have any number of child widgets or none. There is exactly one root widget at the top of the tree that has no parent widget, and all other widgets are directly or indirectly children of this widget (which is wh
42、y its called the root).When new input data is available, Kivy sends out one event per touch. The root widget of the widget tree first receives the event. Depending on the state of the touch, the on_touch_down, on_touch_move or on_touch_up event is dispatched (with the touch as the argument) to the r
43、oot widget, which results in the root widgets corresponding on_touch_down, on_touch_move or on_touch_up event handler being called.Each widget (this includes the root widget) in the tree can choose to either digest or pass the event further. If an event handler returns True it means that the event h
44、as been digested and handled properly. No further processing will happen with that event. Otherwise, the event handler passes the widget on to its own children by calling its superclasss implementation of the respective event handler. This goes all the way up to the base Widget class, which in its t
45、ouch event handlers does nothing but pass the touches to its children:# This is analogous for move/up:def on_touch_down(self, touch): for child in self.children: if child.dispatch('on_touch_down', touch): return TrueThis really is much easier than it first seems. An example of how this can b
46、e used to create nice applications quickly will be given in the following section.Often times you will want to restrict the area on the screen that a widget watches for touches. You can use a widgets collide_point() method to achieve this. You simply pass it the touchs position and it returns True i
47、f the touch is within the watched area or False otherwise. By default, this checks the rectangular region on the screen thats described by the widgets pos (for position; x & y) and size (width & height), but you can override this behaviour in your own class.Your First WidgetIn the following
48、you will be guided through the creation of your first widget. This provides very powerful and important knowledge when programming Kivy applications, as it lets you create completely new user interfaces with custom elements for your specific purpose.Basic ConsiderationsWhen creating an application,
49、you have to ask yourself three main questions:· What data does my application process?· How do I visually represent that data?· How does the user interact with that data?If you want to write a very simple line drawing application for example, you most likely want the user to just draw
50、 on the screen with his fingers. Thats how the user interacts with your application. While doing so, your application would memorize the positions where the users finger was, so that you can later draw lines between those positions. So the points where the fingers were would be your data and the lin
51、es that you draw between these would be your visual representation.In Kivy, an applications user interface is composed of Widgets. Everything that you see on the screen is somehow drawn by a widget. Often you would like to be able to reuse code that you already wrote in a different context, which is
52、 why widgets typically represent one specific instance that answers the three questions above. A widget encapsulates data, defines the users interaction with that data and draws its visual representation. You can then build anything from simple to complex user interfaces by nesting widgets. There ar
53、e many widgets built in, such as buttons, sliders and other common stuff. In many cases, however, you need a custom widget that is beyond the scope of what is shipped with Kivy (e.g. a medical visualization widget).So keep these three questions in mind when you design your widgets. Try to write them
54、 in a minimal and reusable manner (I.e. a widget does exactly what its supposed to do and nothing more. If you need more, write more widgets or compose other widgets of smaller widgets).Paint WidgetWere sure one of your childhood dreams has always been creating your own multitouch paint program. All
55、ow us to help you achieve that. In the following sections you will successively learn how to write a program like that using Kivy. Make sure that you have read and understood Quickstart. You have? Great! Lets get started!Initial StructureLets start by writing the very basic code structure that we ne
56、ed. By the way, all the different pieces of code that are used in this section are also available in the examples/guide/firstwidget directory that comes with Kivy, so you dont need to copy & paste it all the time. Here is the basic code skeleton that we will need: 1 2 3 4 5 6 7 8 9101112131415fr
57、om kivy.app import Appfrom import Widgetclass MyPaintWidget(Widget): passclass MyPaintApp(App): def build(self): return MyPaintWidget()if _name_ = '_main_': MyPaintApp().run()This is actually really simple. Save it as paint.py. If you run it, you should only see a black screen. As you can see, instead of using a built-in widget such as Button (see Quickstart), we are going to write our own widget to do the drawing. We do that by creating a class that inherits from Widget (line 5-6) and although that class does nothing yet, we can still treat it like a normal Kivy wi
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年度個(gè)人主張個(gè)人科技產(chǎn)品借款合同書(智能硬件體驗(yàn))4篇
- 2025年個(gè)人二手車買賣合同(含車輛GPS定位服務(wù))2篇
- 2025年度文化展覽館設(shè)計(jì)裝修合同
- 2025年度股東清算協(xié)議書及清算期間資產(chǎn)保全及保險(xiǎn)合同
- 2025年度專利權(quán)許可使用合同書
- 2025年度門窗廠家與區(qū)域經(jīng)銷商獨(dú)家代理合同
- 2025年度文化創(chuàng)意園區(qū)項(xiàng)目策劃服務(wù)合同樣本
- 2025年度臨時(shí)性活動(dòng)車位租賃合同
- 二零二五年度股權(quán)質(zhì)押擔(dān)保與現(xiàn)代農(nóng)業(yè)合作合同
- 二零二五年度機(jī)場電梯采購與安全檢查服務(wù)合同
- 加強(qiáng)教師隊(duì)伍建設(shè)教師領(lǐng)域?qū)W習(xí)二十屆三中全會(huì)精神專題課
- 2024-2025學(xué)年人教版數(shù)學(xué)七年級(jí)上冊期末復(fù)習(xí)卷(含答案)
- 2024年決戰(zhàn)行測5000題言語理解與表達(dá)(培優(yōu)b卷)
- 四年級(jí)數(shù)學(xué)上冊人教版24秋《小學(xué)學(xué)霸單元期末標(biāo)準(zhǔn)卷》考前專項(xiàng)沖刺訓(xùn)練
- 2025年慢性阻塞性肺疾病全球創(chuàng)議GOLD指南修訂解讀課件
- (完整版)減數(shù)分裂課件
- 銀行辦公大樓物業(yè)服務(wù)投標(biāo)方案投標(biāo)文件(技術(shù)方案)
- 第01講 直線的方程(九大題型)(練習(xí))
- 微粒貸逾期還款協(xié)議書范本
- 人教版七年級(jí)上冊數(shù)學(xué)全冊課時(shí)練習(xí)帶答案
- NBT 47013.4-2015 承壓設(shè)備無損檢測 第4部分:磁粉檢測
評(píng)論
0/150
提交評(píng)論