Kivy что за папка

от admin

Python для Android: Как начать делать кроссплатформенные приложения с Kivy. Часть первая

В этом руководстве приведены шаги, необходимые для создания кроссплатформенного приложения для Android с использованием Python-фреймворка Kivy и Linux Ubuntu. Перед началом установки и запуском Kivy необходимо установить его зависимости. Большая часть времени уйдёт на подготовку рабочей среды Kivy путем установки библиотек, необходимых для его работы. В этом уроке Kivy будет установлен в виртуальной среде.

Используемой платформой будет Linux Ubuntu 18.04 с Python 3.6.5. При запуске Kivy на разных платформах появляются некоторые различия. Чтобы иметь возможность устанавливать библиотеки, перемещаться по каталогам ОС, копировать/удалять/извлекать файлы, запускать скрипты Python, читатель должен иметь базовое представление о командах терминала Linux и Python.

Это руководство имеет следующие разделы:

  1. Введение
  2. Установка зависимостей Kivy
  3. Создание виртуальной среды для установки Kivy
  4. Установка Cython
  5. Установка Kivy
  6. Импорт Kivy
  7. Создание простого приложения Kivy
  8. Установка Buildozer
  9. Создание файла buildozer.spec
  10. Создание приложения для Android с помощью Buildozer
  11. Используемые источники

1. Введение

Kivy используется для создания естественных пользовательских интерфейсов с преимуществами абстракции и модульности. Он отделяет разработчика от ненужных и сложных деталей и просто предоставляет простые API для выполнения сложных задач. В результате вы должны определить, какие бэкенд библиотеки Kivy будет использовать для выполнения своих задач. Мы собираемся использовать SDL (Simple DirectMedia Layer) — кроссплатформенную библиотеку для низкоуровневого доступа к графическому оборудованию через OpenGL. Помимо SDL, другие библиотеки, такие как GStreamer, используются для обработки аудио и видео. Поскольку такие библиотеки написаны на C, нам также потребуется Cython.

2. Установка зависимостей Kivy

Основываясь на инструкциях по установке Kivy на Linux (https://kivy.org/docs/installation/installation-linux.html), здесь перечислены необходимые библиотеки для установки SDL2 и GStreamer. Обратите внимание, что вы можете выбрать версию Python для использования в Kivy с помощью python и python-dev для Python 2 или с помощью python3 и python3-dev для Python 3. Pip также находится в перечисленном ниже списке для последующего использования в подготовке виртуальной среды Kivy.

3. Создание виртуальной среды для установки Kivy

После подготовки зависимостей Kivy мы можем начать установку самого Kivy, создав его виртуальную среду. Нет необходимости использовать виртуальную среду для запуска Kivy, но есть рекомендация отделить Kivy от других уже существующих проектов.

Перед началом создания виртуальной среды мы должны убедиться, что инструменты, необходимые для ее создания, уже установлены и обновлены. Следующие команды гарантируют, что инструменты virtualenv и setuptools уже существуют и обновлены.

virtualenv используется для создания изолированной среды Python. Для получения дополнительной информации о преимуществах виртуальной среды вы можете посетить страницу https://virtualenv.pypa.io/en/stable/. setuptools используется для упаковки проектов Python.

После этого мы готовы создать виртуальную среду Kivy. Следующая команда создает среду с названием mykivyinstall.

Аргумент —no-site-packages используется для изоляции среды от основной установки Python. Это делается для того, чтобы вы могли свободно работать с этим проектом, не затронув другие.

После введения этой команды мы ожидаем получить новую папку в текущем каталоге, названную в соответствии с именем виртуальной среды, как показано на рисунке 1.

В предыдущей команде будет использоваться обычный интерпретатор Python внутри среды. Это может быть Python 2, а мы работаем с Python 3. По этой причине мы могли бы явно указать, какой интерпретатор Python использовать с использованием ключа -p, как в следующей команде:

После создания виртуальной среды мы можем активировать её, чтобы начать установку Kivy. Она может быть активирована следующей командой.

Точка (.) в предыдущей команде представляет собой встроенную команду, которая выполняет содержимое файла, переданного в качестве аргумента. Это синоним источника команды. В результате предыдущая команда идентична этой команде:

Командная строка должна измениться после активации виртуальной среды и начать выглядеть следующим образом:

4. Установка Cython

Перед установкой Kivy Cython должен быть установлен в такой же среде в соответствии со следующей командой:

Обратите внимание, что версия Cython зависит от версии Kivy, которая будет установлена. В данный момент последняя версия Kivy1.10.0, и для нее требуется Cython 0.25.2, и именно поэтому она используется в приведенной выше команде. После этого мы готовы к установке Kivy.

5. Установка Kivy

Kivy можно установить с помощью pip в соответствии со следующей командой:

После этой команды ожидается, что Kivy будет загружен и установлен автоматически. Но учтите, что установка Kivy — это трудная часть, потому что существует множество зависимостей, которые являются варьируются в зависимости от используемой машины, платформы и библиотек, которые у вас уже есть и которых нету. Процесс не является простым и прямолинейным, поэтому вы должны искать альтернативные способы решения ошибок установки. Например, Kivy можно установить с помощью wheel-файла или путем клонирования его проекта github в соответствии со следующей командой:

6. Импорт Kivy

При достижении этого этапа, ожидается, что Kivy уже установлен и успешно работает на вашем компьютере. Мы можем протестировать эту среду, импортировав Kivy, как показано на рисунке 2. Виртуальная среда активирована, Python активирован и Kivy успешно импортирован.

Убедившись, что Kivy работает хорошо, мы готовы создать наше первое приложение Kivy.

На этом конец первой части. Во второй части мы приступим непосредственно к написанию приложения и переносу его на Android-платформу.

Kivy. Сборка пакетов под Android и никакой магии


Во вчерашней статье Python в Mobile development, в которой речь шла о библиотеке KivyMD (коллекции виджетов в стиле Material Design для использования их в кроссплатформенном фреймворке Kivy), в комментариях меня попросили рассказать о процессе сборки пакета для платформы Android. Для многих этот процесс, к сожалению, был и остается чем-то из ряда магического шаманства и не подъёмным для новичков делом. Что ж, давайте разбираться, так ли на самом деле все сложно и действительно ли я маг и волшебник.

Конечно, мог бы! Итак, вы написали свой код на Python и Kivy. Что нужно для того, чтобы это можно было запустить на Android устройствах? Перейдите в репозиторий KivyMD и вы увидите, что в этой инструкции уже давно прописаны шаги, которые позволят вам собрать APK пакет:

  1. Загрузите XUbuntu 18.04

Все! Теперь у вас есть виртуальная машина для сборки APK пакетов для приложений Kivy! Что дальше? Давайте, собственно, займемся сборкой тестового приложения. Создайте в домашнем каталоге вашей виртуальной машины директорию TestKivyMD с пустым файлом main.py:


Далее откройте файл main.py и напишите код нашего тестового приложения, которое будет использовать библиотеку KivyMD:

Сохраните, откройте терминал в директории с файлом main.py и установите библиотеку KivyMD:

После установки можно протестировать наш код:

Результатом работы скрипта будет экран с Toolbar и одной кнопкой «Hello World»:


Дальше нам нужно создать файл спецификации buildozer.spec, который должен располагаться в той же директории, что и файл main.py:


Если вы не закрывали терминал (если терминал был закрыт, откройте его в директории TestKivyMD), введите команду:

Эта команда создаст дефолтный файл спецификации. Откройте его и отредактируйте:

Здесь все понятно поэтому дополнительные комментарии излишни. Почитайте внимательно дефолтную спецификацию, в ней можно указать путь к иконке, пресплеш при загрузке приложения и многое другое. Я оставил лишь то, что нам сейчас нужно для сборки нашего тестового пакета. И, собственно, запускаем процесс сборки командой в терминале:

Можете смело идти на кухню и заваривать кофе, потому что в первый раз процесс загрузки и компиляции библиотек займет очень много времени. Все последующие сборки проходят за 10-20 секунд.

Кофе выпит и самое время заглянуть в терминал:


Вуаля! Наше приложение построено! Самое время закинуть его на смартфон и запустить:

Все работает! И оказывается не все так сложно, как казалось.

Также меня спрашивали:


Ни у Flutter ни у React Native нет преимуществ перед языком разметки Kivy Language, которая позволяет создавать и позиционировать лайоуты и виджеты. Как по мне, то, как строится UI во Flutter — это самое настоящее извращение. Придумать это мог только больной на голову человек. Чтобы не быть голословным, давайте посмотрим на код Flutter и код Kivy одного и того же простейшего приложения… Выглядеть оно будет следующим образом:

А вот абсолютно тоже самое, но с использованием Kivy и KivyMD:

По-моему, вывод очевиден и не нуждается в моем комментировании…

Надеюсь, был вам полезен. Оставляю опрос на тему «Удалось ли вам построить приложение для Андроид».

Name already in use

kivy / doc / sources / gettingstarted / installation.rst

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Installation for Kivy version |kivy_version_bold| . Read the :ref:`changelog here <changelog>` . For other Kivy versions, select the documentation from the dropdown on the top left.

Kivy |kivy_version| officially supports Python versions |python_versions_bold| .

Platform Installation Packaging
w_logo Windows :ref:`pip<install-pip>` :ref:`PyInstaller<packaging-win>`
m_logo macOS :ref:`pip<install-pip>` , :ref:`Kivy.app<osx-app>` :ref:`Kivy.app<packaging-osx-sdk>` , :ref:`PyInstaller<osx_pyinstaller>`
l_logo Linux :ref:`pip<install-pip>` , :ref:`PPA<linux-ppa>`
b_logo * BSD (FreeBSD. ) :ref:`pip<install-pip>`
r_logo RPi :ref:`pip<install-pip>`
a_logo Android :ref:`python-for-android<packaging_android>` :ref:`python-for-android<packaging_android>`
iOS :ref:`kivy-ios<packaging_ios>` :ref:`kivy-ios<packaging_ios>`
c_logo Anaconda :ref:`conda<install-conda>`

The easiest way to install Kivy is with pip , which installs Kivy using either a :ref:`pre-compiled wheel<pip-wheel>` , if available, otherwise from source (see below).

Kivy provides :ref:`pre-compiled wheels<kivy-wheel-install>` for the supported Python versions on Windows, macOS, Linux, and RPi.

If no wheels are available pip will build the package from sources (i.e. on * BSD).

Alternatively, installing :ref:`from source<kivy-source-install>` is required for newer Python versions not listed above or if the wheels do not work or fail to run properly.

Setup terminal and pip

Before Kivy can be installed, Python and pip needs to be :ref:`pre-installed<install-python>` . Then, start a :ref:`new terminal<command-line>` that has :ref:`Python available<install-python>` . In the terminal, update pip and other installation dependencies so you have the latest version as follows (for linux users you may have to substitute python3 instead of python and also add a —user flag in the subsequent commands outside the virtual environment):

Create virtual environment

Create a new virtual environment for your Kivy project. A virtual environment will prevent possible installation conflicts with other Python versions and packages. It’s optional but strongly recommended:

Create the virtual environment named kivy_venv in your current directory:

Activate the virtual environment. You will have to do this step from the current directory every time you start a new terminal. This sets up the environment so the new kivy_venv Python is used.

For Windows default CMD, in the command line do:

If you are in a bash terminal on Windows, instead do:

If you are in linux or macOS, instead do:

Your terminal should now preface the path with something like (kivy_venv) , indicating that the kivy_venv environment is active. If it doesn’t say that, the virtual environment is not active and the following won’t work.

Finally, install Kivy using one of the following options:

The simplest is to install the current stable version of kivy and optionally kivy_examples from the kivy-team provided PyPi wheels. Simply do:

This also installs the minimum dependencies of Kivy. To additionally install Kivy with audio/video support, install either kivy[base,media] or kivy[full] . See :ref:`Kivy’s dependencies<kivy-dependencies>` for the list of selectors.

For the Raspberry Pi, you must additionally install the dependencies listed in :ref:`source dependencies<install-source-rpi>` before installing Kivy above.

If a wheel is not available or is not working, Kivy can be installed from source with some additional steps. Installing from source means that Kivy will be installed from source code and compiled directly on your system.

In past, for macOS, Linux and BSD Kivy required the installation of the SDL dependencies from package managers (e.g. apt or brew ). However, this is no longer officially supported as the version of SDL provided by the package managers is often outdated and may not work with Kivy as we try to keep up with the latest SDL versions in order to support the latest features and bugfixes.

You can still install the SDL dependencies from package managers if you wish, but we no longer offer support for this.

Instead, we recommend installing the SDL dependencies from source. This is the same process our CI uses to build the wheels. The SDL dependencies are built from source and installed into a specific directory.

With all the build tools installed, you can now install the SDL dependencies from source for SDL support (this is not needed on Windows as we provide pre-built SDL dependencies for Windows)

In order to do so, we provide a script that will download and build the SDL dependencies from source. This script is located in the tools directory of the Kivy repository.

Create a directory to store the self-built dependencies and change into it:

Then download the build tool script, according to your platform:

On macOS:

On Linux:

Make the script executable:

Finally, run the script:

The script will download and build the SDL dependencies from source. It will also install the dependencies into a directory named kivy-dependencies. This directory will be used by Kivy to build and install Kivy from source with SDL support.

Kivy will need to know where the SDL dependencies are installed. To do so, you must set the KIVY_DEPS_ROOT environment variable to the path of the kivy-dependencies directory. For example, if you are in the kivy-deps-build directory, you can set the environment variable with:

With the dependencies installed, and KIVY_DEPS_ROOT set you can now install Kivy into the virtual environment.

To install the stable version of Kivy, from the terminal do:

To install the latest cutting-edge Kivy from master, instead do:

If you want to install Kivy from a different branch, from your forked repository, or from a specific commit (e.g. to test a fix from a user’s PR) replace the corresponding components of the url.

For example to install from the stable branch, the url becomes https://github.com/kivy/kivy/archive/stable.zip . Or to try a specific commit hash, use e.g. https://github.com/kivy/kivy/archive/3d3e45dda146fef3f4758aea548da199e10eb382.zip

Pre-release, pre-compiled wheels

To install a pre-compiled wheel of the last pre-release version of Kivy, instead of the current stable version, add the —pre flag to pip:

This will only install a development version of Kivy if one was released to PyPi. Instead, one can also install the latest cutting-edge :ref:`Nightly wheels <nightly-win-wheels>` from the Kivy server with:

It is done in two steps, because otherwise pip may ignore the wheels on the server and install an older pre-release version from PyPi.

For the Raspberry Pi, remember to additionally install the dependencies listed in :ref:`source dependencies<install-source-rpi>` before installing Kivy above.

If you want to edit Kivy before installing it, or if you want to try fixing some Kivy issue and submit a pull request with the fix, you will need to first download the Kivy source code. The following steps assumes git is pre-installed and available in the terminal.

The typical process is to clone Kivy locally with:

This creates a kivy named folder in your current path. Next, follow the same steps of the :ref:`Installing from source <_kivy-source-install>` above, but instead of installing Kivy via a distribution package or zip file, install it as an editable install.

In order to do so, first change into the Kivy folder you just cloned:: and then install Kivy as an editable install:

Now, you can use git to change branches, edit the code and submit a PR. Remember to compile Kivy each time you change cython files as follows:

Or if using bash or on Linux, simply do:

To run the test suite, simply run:

or in bash or Linux:

On * BSD Unix remember to use gmake (GNU) in place of make (BSD).

Checking the demo

Kivy should now be installed. You should be able to import kivy in Python or, if you installed the Kivy examples, run the demo.

in bash, Linux and macOS:

The exact path to the Kivy examples directory is also stored in kivy.kivy_examples_dir .

The 3d monkey demo under kivy-examples/3Drendering/main.py is also fun to see.

Installation using Conda

If you use Anaconda, you can install Kivy with its package manager Conda using:

Do not use pip to install kivy if you’re using Anaconda, unless you’re installing from source.

Installing Kivy’s dependencies

Kivy supports one or more backends for its core providers. E.g. it supports glew, angle, and sdl2 for the graphics backend on Windows. For each category (window, graphics, video, audio, etc.), at least one backend must be installed to be able to use the category.

To facilitate easy installation, we provide extras_require groups that will install selected backends to ensure a working Kivy installation. So one can install Kivy more simply with e.g.«pip install «kivy[base,media,tuio]» « . The full list of selectors and the packages they install is listed in setup.py. The exact packages in each selector may change in the future, but the overall goal of each selector will remain as described below.

We offer the following selectors:

base: The minimum typical dependencies required for Kivy to run, not including video/audio. media: Only the video/audio dependencies required for Kivy to be able to play media. full: All the typical dependencies required for Kivy to run, including video/audio and most optional dependencies. dev: All the additional dependencies required to run Kivy in development mode (i.e. it doesn’t include the base/media/full dependencies). E.g. any headers required for compilation, and all dependencies required to run the tests and creating the docs.

tuio: The dependencies required to make TUIO work (primarily oscpy).

The following selectors install backends packaged as wheels by kivy under the Kivy_deps namespace. They are typically released and versioned to match specific Kivy versions, so we provide selectors to facilitate installation (i.e. instead of having to do pip install kivy kivy_deps.sdl2==x.y.z , you can now do pip install «kivy[sdl2]» to automatically install the correct sdl2 for the Kivy version).

gstreamer: The gstreamer video/audio backend, if it’s available (currently only on Windows) angle: A alternate OpenGL backend, if it’s available (currently only on Windows) sdl2: The window/image/audio backend, if it’s available (currently only on Windows, on macOS, Linux and * BSD Unix is already included in the main Kivy wheel).

glew: A alternate OpenGL backend, if it’s available (currently only on Windows)

Following are the kivy_deps dependency wheels:

kivy_deps.gstreamer is an optional dependency which is only needed for audio/video support. We only provide it on Windows, for other platforms it must be installed independently. Alternatively, use ffpyplayer instead.

kivy_deps.glew and kivy_deps.angle are for OpenGL. You can install both, that is no problem. It is only available on Windows. On other platforms it is not required externally.

One can select which of these to use for OpenGL using the KIVY_GL_BACKEND environment variable: By setting it to glew (the default), angle_sdl2 , or sdl2 . Here, angle_sdl2 is a substitute for glew but requires kivy_deps.sdl2 be installed as well.

kivy_deps.sdl2 is for window/images/audio and optionally OpenGL. It is only available on Windows and is included in the main Kivy wheel for other platforms.

Here we explain how to install Python packages, how to use the command line and what wheels are.

Kivy is written in Python and as such, to use Kivy, you need an existing installation of Python. Multiple versions of Python can be installed side by side, but Kivy needs to be installed as package under each Python version that you want to use Kivy in.

Once Python is installed, open the :ref:`console <command-line>` and make sure Python is available by typing python —version .

How to use the command line

To execute any of the pip or wheel commands given here, you need a command line (here also called console, terminal, shell or bash, where the last two refer to Linux / * BSD Unix style command lines) and Python must be on the PATH.

The default command line on Windows is the command prompt, short cmd. The quickest way to open it is to press Win+R on your keyboard. In the window that opens, type cmd and then press enter.

Alternative Linux style command lines on Windows that we recommend are Git for Windows or Mysys.

Note, the default Windows command line can still be used, even if a bash terminal is installed.

To temporarily add your Python installation to the PATH, simply open your command line and then use the cd command to change the current directory to where python is installed, e.g. cd C:\Python37 .

If you have installed Python using the default options, then the path to Python will already be permanently on your PATH variable. There is an option in the installer which lets you do that, and it is enabled by default.

If however Python is not on your PATH, follow the these instructions to add it:

  • Instructions for the windows command line
  • Instructions for bash command lines

What is pip and what are wheels

In Python, packages such as Kivy can be installed with the python package manager, named pip («python install package»).

When installing from source, some packages, such as Kivy, require additional steps, like compilation.

Contrary, wheels (files with a .whl extension) are pre-built distributions of a package that has already been compiled. These wheels do not require additional steps when installing them.

When a wheel is available on pypi.org («Python Package Index») it can be installed with pip . For example when you execute python -m pip install kivy in a command line, this will automatically find the appropriate wheel on PyPI.

When downloading and installing a wheel directly, use the command python -m pip install <wheel_file_name> , for example:

What are nightly wheels

Every day we create a snapshot wheel of the current development version of Kivy (‘nightly wheel’). You can find the development version in the master branch of the Kivy Github repository.

As opposed to the last stable release (which we discussed in the previous section), nightly wheels contain all the latest changes to Kivy, including experimental fixes. For installation instructions, see :ref:`kivy-nightly-install` .

Using the latest development version can be risky and you might encounter issues during development. If you encounter any bugs, please report them.

Create a package for Android¶

You can create a package for android using the python-for-android project. This page explains how to download and use it directly on your own machine (see Packaging your application into APK or AAB ) or use the Buildozer tool to automate the entire process. You can also see Packaging your application for the Kivy Launcher to run kivy programs without compiling them.

For new users, we recommend using Buildozer as the easiest way to make a full APK or AAB. You can also run your Kivy app without a compilation step with the Kivy Launcher app.

Kivy applications can be released on an Android market such as the Play store, with a few extra steps to create a fully signed AAB (Android App Bundle).

The Kivy project includes tools for accessing Android APIs to accomplish vibration, sensor access, texting etc. These, along with information on debugging on the device, are documented at the main Android page .

Buildozer¶

Buildozer is a tool that automates the entire build process. It downloads and sets up all the prerequisites for python-for-android, including the android SDK and NDK, then builds an apk that can be automatically pushed to the device.

Buildozer currently works only in Linux and macOS (You can still use it on Windows via WSL), and can significantly simplify the apk build.

This will install buildozer in your system. Afterwards, navigate to your project directory and run:

This creates a buildozer.spec file controlling your build configuration. You should edit it appropriately 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:

to build, push and automatically run the apk on your device.

Buildozer has many available options and tools to help you, the steps above are just the simplest way to build and run your APK. The full documentation is available here. You can also check the Buildozer README at https://github.com/kivy/buildozer.

Packaging with python-for-android¶

You can also package directly with python-for-android, which can give you more control but requires you to manually download parts of the Android toolchain.

Packaging your application for the Kivy Launcher¶

The Kivy launcher is an Android application that runs any Kivy examples stored on your SD Card. To install the Kivy launcher, you must:

Go on Google Play Store and search for Kivy Launcher from kivy org

Click on Install

Select your phone… And you’re done!

If you don’t have access to the Google Play Store on your phone/tablet, you can download and install the APK manually from https://github.com/kivy/kivy-launcher/releases

Once the Kivy launcher is installed, you can put your Kivy applications in the Kivy directory in your external storage directory (often available at /sdcard even in devices where this memory is internal), e.g.

<yourapplication> should be a directory containing:

The file android.txt must contain:

These options are just a very basic configuration. If you create your own APK using the tools above, you can choose many other settings.

Installation of Examples¶

Kivy comes with many examples, and these can be a great place to start trying the Kivy launcher. You can run them as below:

Run the launcher and select one of the Pictures, Showcase, Touchtracer, Cymunk or other demos…

Release on the market¶

If you have built your own APK with Buildozer or with python-for-android, you can create a release version that may be released on the Play store or other Android markets.

To do this, you must run Buildozer with the release parameter (e.g. buildozer android release ), or if using python-for-android use the —release option to build.py. This creates a release AAB in the bin directory, which you must properly sign and zipalign. The procedure for doing this is described in the Android documentation at https://developer.android.com/studio/publish/app-signing.html#signing-manually — all the necessary tools come with the Android SDK.

Targeting Android¶

Kivy is designed to operate identically across platforms and as a result, makes some clear design decisions. It includes its own set of widgets and by default, builds an APK or AAB with all the required core dependencies and libraries.

It is possible to target specific Android features, both directly and in a (somewhat) cross-platform way. See the Using Android APIs section of the Kivy on Android documentation for more details.

Читать:
Как выключить тихий режим на ноутбуке

Похожие статьи