Установка kivy python 3 на windows инструкция

Table Of Contents

  • Installing Kivy
    • Using pip
      • Setup terminal and pip
      • Create virtual environment
      • Install Kivy
        • Pre-compiled wheels
        • From source
        • Pre-release, pre-compiled wheels
        • Development install
      • Checking the demo
    • Installation using Conda
    • Installing Kivy’s dependencies
    • Python glossary
      • Installing Python
      • How to use the command line
      • What is pip and what are wheels
      • What are nightly wheels

Installation for Kivy version 2.2.1. Read the changelog here.
For other Kivy versions, select the documentation from the dropdown on the top left.

Kivy 2.2.1 officially supports Python versions 3.7 — 3.11.

Platform

Installation

Packaging

w_logo

Windows

pip

PyInstaller

m_logo

macOS

pip, Kivy.app

Kivy.app, PyInstaller

l_logo

Linux

pip, PPA

b_logo

*BSD (FreeBSD,..)

pip

r_logo

RPi

pip

a_logo

Android

python-for-android

python-for-android

i_logo

iOS

kivy-ios

kivy-ios

c_logo

Anaconda

conda

Using pip¶

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

Kivy provides pre-compiled wheels 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 from source is required for newer Python versions not listed
above or if the wheels do not work or fail to run properly.

On RPi, when using a 32 bit OS, wheels are provided for Python 3.7 (Raspberry Pi OS Buster) and Python 3.9 (Raspberry Pi OS Bullseye),
via the PiWheels project. For other Python versions, on 32 bit OSes, you will need to
install from source.

Setup terminal and pip¶

Before Kivy can be installed, Python and pip needs to be pre-installed.
Then, start a new terminal that has
Python available. 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):

python -m pip install --upgrade pip setuptools virtualenv

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:

  1. Create the virtual environment named kivy_venv in your current directory:

    python -m virtualenv kivy_venv
    
  2. 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:

    kivy_venvScriptsactivate
    

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

    source kivy_venv/Scripts/activate
    

    If you are in linux or macOS, instead do:

    source kivy_venv/bin/activate
    

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.

Install Kivy¶

Finally, install Kivy using one of the following options:

Pre-compiled wheels¶

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

python -m pip install "kivy[base]" kivy_examples

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 Kivy’s dependencies for the list of selectors.

From source¶

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.

First install the additional system dependencies listed for each platform:
Windows, macOS,
Linux, *BSD,
RPi

Note

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:

mkdir kivy-deps-build && cd kivy-deps-build

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

On macOS:

curl -O https://raw.githubusercontent.com/kivy/kivy/master/tools/build_macos_dependencies.sh -o build_kivy_deps.sh

On Linux:

curl -O https://raw.githubusercontent.com/kivy/kivy/master/tools/build_linux_dependencies.sh -o build_kivy_deps.sh

Make the script executable:

chmod +x build_kivy_deps.sh

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:

export KIVY_DEPS_ROOT=$(pwd)/kivy-dependencies

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:

python -m pip install "kivy[base]" kivy_examples --no-binary kivy

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

python -m pip install "kivy[base] @ https://github.com/kivy/kivy/archive/master.zip"

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:

python -m pip install --pre "kivy[base]" kivy_examples

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

python -m pip install kivy --pre --no-deps --index-url  https://kivy.org/downloads/simple/
python -m pip install "kivy[base]" --pre --extra-index-url https://kivy.org/downloads/simple/

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.

Development install¶

Note

We suggest to select master or relevant branch/version of doc from top left,
ensuring correct version/branch of kivy git repository you are working with.

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:

git clone https://github.com/kivy/kivy.git

This creates a kivy named folder in your current path. Next, follow the same steps of the
Installing from source 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:

cd kivy
python -m pip install -e ".[dev,full]"

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:

python setup.py build_ext --inplace

Or if using bash or on Linux, simply do:

to recompile.

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.

on Windows:

python kivy_venvsharekivy-examplesdemoshowcasemain.py

in bash, Linux and macOS:

python kivy_venv/share/kivy-examples/demo/showcase/main.py

on *BSD Unix:

python3 kivy_venv/share/kivy-examples/demo/showcase/main.py

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:

conda install kivy -c conda-forge

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:

  • gstreamer (optional)

    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.

  • glew and/or
    angle

    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.

  • sdl2

    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.

Python glossary¶

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

Installing Python¶

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.

To install Python, see the instructions for each platform:
Windows, macOS,
Linux, RPi,
*BSD.

Once Python is installed, open the console 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:

python -m pip install C:Kivy-1.9.1.dev-cp27-none-win_amd64.whl

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 Pre-release, pre-compiled wheels.

Warning

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

Table Of Contents

  • Installation on Windows
    • Installation components
      • Installing Python
      • Source installation Dependencies
    • Making Python available anywhere
      • Double-click method
      • Send-to method

To install Kivy on Windows via pip, please follow the main installation guide.

Installation components¶

Following, are additional information linked to from some of the steps in the
main installation guide, specific to Windows.

Installing Python¶

To install Python on Windows, download it from the main
Python website and follow the
installation steps. You can read about the individual installation options in the
Python guide.

If you installed the
Python launcher,
you will be more easily able to install multiple Python versions side by side
and select, which to run, at each invocation.

Source installation Dependencies¶

To install Kivy from source, please follow the installation guide until you reach the
Kivy install step and then install the compiler below before continuing.

To install kivy from source, you need a compiler. On Windows, the Visual Studio Build Tools are
required, and they are available for free. You can either:

  • Download and install the complete Visual Studio IDE, which contains the build tools.
    This is the easiest approach and the IDE can be downloaded from here.

  • The IDE is very big, so you can also download just the smaller build tools, which are used from the command line.
    The current download (2019) can be found on this page
    under “Tools for Visual Studio 2019”. More info about this topic can be found
    in the Kivy wiki.

Now that the compiler is installed, continue to install Kivy.

Making Python available anywhere¶

There are two methods for launching Python when double clicking on your *.py files.

Double-click method¶

If you only have one Python installed, and if you installed it using the default options, then *.py files are already
associated with your Python. You can run them by double clicking them in the file manager, or by just executing their name in a console window (without having to prepend python).

Alternatively, if they are not assigned, you can do it the following way:

  1. Right click on the Python file (.py file extension) in the file manager.

  2. From the context menu that appears, select Open With

  3. Browse your hard disk drive and find the python.exe file that you want
    to use (e.g. in the the virtual environment). Select it.

  4. Select “Always open the file with…” if you don’t want to repeat this
    procedure every time you double click a .py file.

  5. You are done. Open the file.

Send-to method¶

You can launch a .py file with Python using the Send to menu:

  1. Browse to the python.exe you want to use. Right click on it and
    copy it.

  2. Open Windows Explorer (the file explorer in Windows 8), and to go the address
    ‘shell:sendto’. You should get the special Windows directory SendTo.

  3. Paste the previously copied python.exe file as a shortcut.

  4. Rename it to python <python-version>. E.g. python39.

You can now execute your application by right clicking on the .py file ->
“Send To” -> “python <python-version>”.

Beginning with 1.9.1 we provide binary
wheels
for Kivy and all its dependencies to be used with an existing Python
installation. See Installation.

We also provide nightly wheels generated using Kivy
master. See Nightly wheel installation.
See also Upgrading from a previous Kivy dist. If installing kivy to an alternate
location
and not to site-packages, please see Installing Kivy to an alternate location.

Note

For Python < 3.5 we use the MinGW compiler. However, for Python 3.5+ on
Windows we currently only support the MSVC compiler
because of the following Python
issue 4709 about MinGW.
Generally this should make no difference when using precompiled wheels.

To use Kivy you need Python.
Multiple versions of Python can be installed side by side, but Kivy needs to
be installed for each Python version that you want to use Kivy.

Installation¶

Now that python is installed, open the Command line and make sure
python is available by typing python --version. Then, do the following to
install.

  1. Ensure you have the latest pip and wheel:

    python -m pip install --upgrade pip wheel setuptools
    
  2. Install the dependencies (skip gstreamer (~120MB) if not needed, see
    Kivy’s dependencies):

    python -m pip install docutils pygments pypiwin32 kivy.deps.sdl2 kivy.deps.glew
    python -m pip install kivy.deps.gstreamer
    

    For Python 3.5 only we additionally offer angle which can be used instead of glew
    and can be installed with:

    python -m pip install kivy.deps.angle
    
  3. Install kivy:

    python -m pip install kivy
    
  4. (Optionally) Install the kivy examples:

    python -m pip install kivy_examples
    

    The examples are installed in the share directory under the root directory where python is installed.

That’s it. You should now be able to import kivy in python or run a basic
example if you installed the kivy examples:

python sharekivy-examplesdemoshowcasemain.py

What are wheels, pip and wheel¶

In Python, packages such as Kivy can be installed with the python package
manager, pip. Some packages such as Kivy
require additional steps, such as compilation, when installing using the Kivy
source code with pip. Wheels (with a .whl extension) are pre-built
distributions of a package that has already been compiled and do not require
additional steps to install.

When hosted on pypi one installs a wheel
using pip, e.g. python -m pip install kivy. When downloading and
installing a wheel directly, python -m pip install wheel_file_name is used,
such as:

python -m pip install C:Kivy-1.9.1.dev-cp27-none-win_amd64.whl

Nightly wheel installation¶

Warning

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

Snapshot wheels of current Kivy master are created on every commit to the
master branch of kivy repository. They can be found
here. To use them, instead of
doing python -m pip install kivy we’ll install one of these wheels as
follows.

  • Python 2.7, 32bit
  • Python 3.4, 32bit
  • Python 3.5, 32bit
  • Python 3.6, 32bit
  • Python 2.7, 64bit
  • Python 3.4, 64bit
  • Python 3.5, 64bit
  • Python 3.6, 64bit
  1. Perform steps 1 and 2 of the above Installation section.
  2. Download the appropriate wheel for your system.
  3. Install it with python -m pip install wheel-name where wheel-name
    is the name of the renamed file and add deps to the PATH.

Kivy examples are separated from the core because of their size. The examples
can be installed separately on both Python 2 and 3 with this single wheel:

  • Kivy examples

Kivy’s dependencies¶

We offer wheels for Kivy and its dependencies separately so only desired
dependencies need be installed. The dependencies are offered as
optional sub-packages of kivy.deps, e.g. kivy.deps.sdl2.

Currently on Windows, we provide the following dependency wheels:

  • gstreamer for audio and video
  • glew and/or
    angle (3.5 only) for OpenGL
  • sdl2 for control and/or OpenGL.

One can select which of these to use for OpenGL use using the
KIVY_GL_BACKEND envrionment variable by setting it to glew
(the default), angle, or sdl2. angle is currently
in an experimental phase as a substitute for glew on Python
3.5 only.

gstreamer is an optional dependency which only needs to be
installed if video display or audio is desired. ffpyplayer
is an alternate dependency for audio or video.

Command line¶

Know your command line. To execute any of the pip
or wheel commands, one needs a command line tool with python on the path.
The default command line on Windows is
Command Prompt, and the
quickest way to open it is to press Win+R on your keyboard, type cmd
in the window that opens, and then press enter.

Alternate linux style command shells that we recommend is
Git for Windows which offers a bash
command line as well as
git. Note, CMD can still be used even if bash is
installed.

Walking the path! To add your python 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:Python27. Alternatively if you only have one
python version installed, permanently add the python directory to the path for
cmd or
bash.

Use development Kivy¶

Warning

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

To compile and install kivy using the kivy
source code or to use
kivy with git rather than a wheel there are some additional steps:

  1. Both the python and the PythonScripts directories must be on
    the path. They must be on the path every time you recompile kivy.

  2. Ensure you have the latest pip and wheel with:

    python -m pip install --upgrade pip wheel setuptools
    
  3. Get the compiler.
    For Python < 3.5 we use mingwpy as follows.

    1. Create the
      pythonLibdistutilsdistutils.cfg file and add the two lines:

      [build]
      compiler = mingw32
      
    2. Install MinGW with:

      python -m pip install -i https://pypi.anaconda.org/carlkl/simple mingwpy
      

    For Python 3.5 we use the MSVC compiler. For 3.5,
    Visual Studio 2015 is
    required, which is availible for free. Just download and install it and
    you’ll be good to go.

    Visual Studio is very big so you can also use the smaller,
    Visual C Build Tools instead.

  4. Set the environment variables. On windows do:

    set USE_SDL2=1
    set USE_GSTREAMER=1
    

    In bash do:

    export USE_SDL2=1
    export USE_GSTREAMER=1
    

    These variables must be set everytime you recompile kivy.

  5. Install the other dependencies as well as their dev versions (you can skip
    gstreamer and gstreamer_dev if you aren’t going to use video/audio):

    python -m pip install cython docutils pygments pypiwin32 kivy.deps.sdl2 
    kivy.deps.glew kivy.deps.gstreamer kivy.deps.glew_dev kivy.deps.sdl2_dev 
    kivy.deps.gstreamer_dev
    
  6. If you downloaded or cloned kivy to an alternate location and don’t want to
    install it to site-packages read the next section.

  7. Finally compile and install kivy with pip install filename, where
    filename can be a url such as
    https://github.com/kivy/kivy/archive/master.zip for kivy master, or the
    full path to a local copy of a kivy.

Compile Kivy¶

  1. Start installation of Kivy cloned from GitHub:

    python -m pip install kivy.
    

If the compilation succeeds without any error, Kivy should be good to go. You
can test it with running a basic example:

python sharekivy-examplesdemoshowcasemain.py

Installing Kivy to an alternate location¶

In development Kivy is often installed to an alternate location and then
installed with:

python -m pip install -e location

That allows Kivy to remain in its original location while being available
to python, which is useful for tracking changes you make in Kivy for example
directly with Git.

To achieve using Kivy in an alternate location extra tweaking is required.
Due to this issue wheel and
pip install the dependency wheels to pythonLibsite-packageskivy. So
they need to be moved to your actual kivy installation from site-packages.

After installing the kivy dependencies and downloading or cloning kivy to your
favorite location, do the following:

  1. Move the contents of pythonLibsite-packageskivydeps to
    your-pathkivydeps where your-path is the path where your kivy is
    located.
  2. Remove the pythonLibsite-packageskivy directory altogether.
  3. From pythonLibsite-packages move all kivy.deps.*.dist-info
    directories to your-path right next to kivy.

Now you can safely compile kivy in its current location with one of these
commands:

> make
> mingw32-make
> python -m pip install -e .
> python setup.py build_ext --inplace

If kivy fails to be imported, you probably didn’t delete all the
*.dist-info folders and and the kivy or kivy.deps* folders from
site-packages.

Making Python available anywhere¶

There are two methods for launching python on your *.py files.

Double-click method¶

If you only have one Python installed, you can associate all *.py files
with your python, if it isn’t already, and then run it by double clicking. Or
you can only do it once if you want to be able to choose each time:

  1. Right click on the Python file (.py file extension) of the application you
    want to launch
  2. From the context menu that appears, select Open With
  3. Browse your hard disk drive and find the file python.exe that you want
    to use. Select it.
  4. Select “Always open the file with…” if you don’t want to repeat this
    procedure every time you double click a .py file.
  5. You are done. Open the file.

Send-to method¶

You can launch a .py file with our Python using the Send-to menu:

  1. Browse to the python.exe file you want to use. Right click on it and
    copy it.
  2. Open Windows explorer (File explorer in Windows 8), and to go the address
    ‘shell:sendto’. You should get the special Windows directory SendTo
  3. Paste the previously copied python.exe file as a shortcut.
  4. Rename it to python <python-version>. E.g. python27-x64

You can now execute your application by right clicking on the .py file ->
“Send To” -> “python <python-version>”.

Upgrading from a previous Kivy dist¶

To install the new wheels to a previous Kivy distribution all the files and
folders, except for the python folder should be deleted from the distribution.
This python folder will then be treated as a normal system installed python and
all the steps described in Installation can then be continued.

В наши дни каждый разработчик может столкнуться с необходимостью работы над мобильным или веб-приложением на Python. В Python нет встроенных инструментов для мобильных устройств, тем не менее существуют пакеты, которые можно использовать для создания мобильных приложений. Это Kivy, PyQt и даже библиотека Toga от Beeware.

Содержание

  • Принципы работы фреймворка Kivy Python
  • Установка Kivy
  • Работа с виджетами в Kivy
  • Запуск программы «Hello, Kivy!»
  • Отображение виджета Image в Kivy Python
  • Разметка (Layout) в UI Kivy
  • Добавление событий в Kivy
  • Использование языка дизайна KV
  • Создание приложения Kivy Python
  • Создаем apk приложения для Android на Python
  • Создание приложений для iPhone (iOS) на Python
  • Создание exe приложений для Windows на Python используя Kivy
  • Создание приложений для macOS на Python используя Kivy

Библиотеки являются основными элементами мобильного мира Python. Однако, говоря о Kivy, нельзя игнорировать преимущества данного фреймворка при работе с мобильными приложениями. Внешний вид приложения автоматически подстраивается под все платформы, разработчику при этом не нужно компилировать код после каждой поправки. Кроме того, здесь для создания приложений можно использовать чистый синтаксис Python.

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

  • Работа с виджетами Kivy;
  • Планировка UI и лейауты;
  • Добавление событий;
  • Использование языка KV;
  • Создание приложения-калькулятора;
  • Упаковка приложения для iOS, Android, Windows и macOS.

Разбор данного руководства предполагает, что читатель знаком с объектно-ориентированным программированием. Для введения в курс дела можете просмотреть статью об Объектно-ориентированном программировании (ООП) в Python 3.

Приступим!

Принципы работы фреймворка Kivy Python

Kivy был создан в 2011 году. Данный кросс-платформенный фреймворк Python работает на Windows, Mac, Linux и Raspberry Pi. В дополнение к стандартному вводу через клавиатуру и мышь он поддерживает мультитач. Kivy даже поддерживает ускорение GPU своей графики, что во многом является следствием использования  OpenGL ES2. У проекта есть лицензия MIT, поэтому библиотеку можно использовать бесплатно и вкупе с коммерческим программным обеспечением.

Во время разработки приложения через Kivy создается интуитивно понятный интерфейс (Natural user Interface), или NUI. Его главная идея в том, чтобы пользователь мог легко и быстро приспособиться к программному обеспечению без чтения инструкций.

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

Установка Kivy

У Kivy есть множество зависимостей, поэтому лучше устанавливать его в виртуальную среду Python. Можно использовать встроенную библиотеку Python venv или же пакет virtualenv.

Виртуальная среда Python создается следующим образом:

$ python3 m venv my_kivy_project

По ходу данного действия исполняемый файл Python 3 будет скопирован в папку под названием my_kivy_project, куда также будут добавлено несколько других папок.

Есть вопросы по Python?

На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!

Telegram Чат & Канал

Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!

Паблик VK

Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!

Для использования виртуальной среды ее нужно активировать. На Mac или Linux это можно сделать, выполнив следующую команду, будучи внутри папки my_kivy_project:

Команда для Windows точно такая же, но активировать скрипт нужно в другом месте — через папку Scripts, а не bin.

После активации виртуальной среды Python можно запустить pip для установки Kivy. На Linux и Mac нужно выполнить следующую команду:

$ python m pip install kivy

Инсталляция на Windows несколько сложнее. В официальной документации фреймворка изучите пункт, касающийся установки Kivy на Windows. Пользователи Mac также могут скачать файл dmg и установить Kivy данным образом.

В случае возникновения проблем во время установки Kivy на вашу платформу изучите дополнительные инструкции, с которыми можно ознакомиться через страницу загрузки.

Работа с виджетами в Kivy

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

Запуск программы «Hello, Kivy!»

Принцип работы Kivy можно уловить, взглянув на следующее приложение «Hello, World!»:

from kivy.app import App

from kivy.uix.label import Label

class MainApp(App):

    def build(self):

        label = Label(text=‘Hello from Kivy’,

                      size_hint=(.5, .5),

                      pos_hint={‘center_x’: .5, ‘center_y’: .5})

        return label

if __name__ == ‘__main__’:

    app = MainApp()

    app.run()

Каждому приложению Kivy требуется создать подкласс App и переопределить метод build().  Сюда вы помещаете код UI или вызываете другие функции, которые определяют код UI. В данном случае создается виджет Label и передается text, size_hint и pos_hint. Последние два аргумента не обязательны.

size_hint говорит Kivy о размерах что нужно использовать при создании виджета. Используются два числа:

  1. Первое число x указывает на размер ширины элемента управления.
  2. Второе число y указывает на размер высоты элемента управления.

Значение обоих чисел должно быть в промежутке между 0 и 1. Значение по обоих показателей по умолчанию равно 1. Также можно задействовать pos_hint, что используется для позиционирования виджета. В коде, размещенном выше, указывается, что виджет должен быть размещен в центре осей x и y.

Для запуска приложения нужно инициализировать класс MainApp и вызвать метод run(). После этих действий на экране появится следующее:

App Hello from Kivy

Kivy также выводит в stdout довольно много текста:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

[INFO   ] [Logger      ] Record log in /home/mdriscoll/.kivy/logs/kivy_190607_2.txt

[INFO   ] [Kivy        ] v1.11.0

[INFO   ] [Kivy        ] Installed at «/home/mdriscoll/code/test/lib/python3.6/site-packages/kivy/__init__.py»

[INFO   ] [Python      ] v3.6.7 (default, Oct 22 2018, 11:32:17)

[GCC 8.2.0]

[INFO   ] [Python      ] Interpreter at «/home/mdriscoll/code/test/bin/python»

[INFO   ] [Factory     ] 184 symbols loaded

[INFO   ] [Image       ] Providers: img_tex, img_dds, img_sdl2, img_gif (img_pil, img_ffpyplayer ignored)

[INFO   ] [Text        ] Provider: sdl2([‘text_pango’] ignored)

[INFO   ] [Window      ] Provider: sdl2([‘window_egl_rpi’] ignored)

[INFO   ] [GL          ] Using the «OpenGL» graphics system

[INFO   ] [GL          ] Backend used <sdl2>

[INFO   ] [GL          ] OpenGL version <b‘4.6.0 NVIDIA 390.116’>

[INFO   ] [GL          ] OpenGL vendor <b‘NVIDIA Corporation’>

[INFO   ] [GL          ] OpenGL renderer <b‘NVS 310/PCIe/SSE2’>

[INFO   ] [GL          ] OpenGL parsed version: 4, 6

[INFO   ] [GL          ] Shading version <b‘4.60 NVIDIA’>

[INFO   ] [GL          ] Texture max size <16384>

[INFO   ] [GL          ] Texture max units <32>

[INFO   ] [Window      ] auto add sdl2 input provider

[INFO   ] [Window      ] virtual keyboard not allowed, single mode, not docked

[INFO   ] [Base        ] Start application main loop

[INFO   ] [GL          ] NPOT texture support is available

Это может быть полезно для отладки приложения.

Далее добавим виджет Image и посмотрим, чем он отличается от Label.

Отображение виджета Image в Kivy Python

В Kivy есть несколько видов виджетов, связанных с изображениями. Для загрузки картинок с жесткого диска можно задействовать Image, а при использовании адреса URL подойдет AsyncImage. К следующем примере берется стандартный класс Image:

from kivy.app import App

from kivy.uix.image import Image

class MainApp(App):

    def build(self):

        img = Image(source=‘/path/to/real_python.png’,

                    size_hint=(1, .5),

                    pos_hint={‘center_x’:.5, ‘center_y’:.5})

        return img

if __name__ == ‘__main__’:

    app = MainApp()

    app.run()

В данном коде импортируется Image из подпакета kivy.uix.image. Класс Image принимает много разных параметров, однако единственным для нас нужным является source, что указывает Kivy, какое изображение должно быть загружено. Здесь передается полный путь к выбранному изображению. Оставшаяся часть кода такая же, как и в прошлом примере.

После запуска кода должно выводиться нечто подобное:

Load Image Kivy

Текст из предыдущего примера был заменен картинкой.

Теперь рассмотрим, как добавить и оптимально расположить несколько виджетов в приложении.

Разметка (Layout) в UI Kivy

У каждого фреймворка есть свой собственный метод для размещения виджетов. К примеру, в wxPython используются классификаторы, а в Tkinter будет задействован лейаут, или менеджер геометрии. В Kivy за это отвечают Лейауты (Layouts). Доступно несколько различных типов Лейаутов. Чаще всего используются следующие виды:

  • BoxLayout;
  • FloatLayout;
  • GridLayout.

Найти полный список доступных Лейаутов можно в документации Kivy. Рабочий исходный код можно найти в kivy.uix.

Рассмотрим BoxLayout на примере следующего кода:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

import kivy

import random

from kivy.app import App

from kivy.uix.button import Button

from kivy.uix.boxlayout import BoxLayout

red = [1,0,0,1]

green = [0,1,0,1]

blue =  [0,0,1,1]

purple = [1,0,1,1]

class HBoxLayoutExample(App):

    def build(self):

        layout = BoxLayout(padding=10)

        colors = [red, green, blue, purple]

        for i in range(5):

            btn = Button(text=«Button #%s» % (i+1),

                         background_color=random.choice(colors)

                         )

            layout.add_widget(btn)

        return layout

if __name__ == «__main__»:

    app = HBoxLayoutExample()

    app.run()

Здесь из kivy.uix.boxlayout импортируется модуль BoxLayout и затем устанавливается. После этого создается список цветов, которые представляют собой цвета RGB (Red-Blue-Green).

В конечном итоге формируется цикл для range из 5, результатом чего является кнопка btn для каждой итерации. Сделаем вещи немного интереснее и поставим в качестве фона кнопки background_color случайный цвет. Теперь можно добавить кнопку в лейаут при помощи layout.add_widget(btn).

После запуска кода выведется нечто подобное:

Kivy Hbox Layout

Здесь представлены 5 кнопок, окрашенных случайным образом, по одной для каждой итерации цикла for.

Во время создания лейаута следует учитывать следующие аргументы:

  • padding: Отступ padding между лейаутом и его дочерними элементами уточняется в пикселях. Для этого можно выбрать один из трех способов:
    1. Список из четырех аргументов: [padding_left, padding_top, padding_right, padding_bottom]
    2. Список из двух аргументов: [padding_horizontal, padding_vertical]
    3. Один аргумент: padding=10
  • spacing: При помощи данного аргумента добавляется расстояние между дочерними виджетами.
  • orientation: Позволяет изменить значение orientation для BoxLayout по умолчанию — с горизонтального на вертикальное.

Добавление событий в Kivy

Как и многие другие инструментарии GUI, по большей части Kivy полагается на события. Фреймворк отзывается на нажатие клавиш, кнопки мышки или прикосновение к сенсорному экрану. В Kivy задействован концепт Часов (Clock), что дает возможность создать своего рода график для вызова определенных функций в будущем.

В Kivy также используется концепт Свойств (Properties), что работает с EventDispatcher. Свойства помогают осуществить проверку достоверности. Они также запускают события, когда виджет меняет размер или позицию.

Добавим событие для кнопки из предыдущего кода:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

from kivy.app import App

from kivy.uix.button import Button

class MainApp(App):

    def build(self):

        button = Button(text=‘Hello from Kivy’,

                        size_hint=(.5, .5),

                        pos_hint={‘center_x’: .5, ‘center_y’: .5})

        button.bind(on_press=self.on_press_button)

        return button

    def on_press_button(self, instance):

        print(‘Вы нажали на кнопку!’)

if __name__ == ‘__main__’:

    app = MainApp()

    app.run()

В данном коде вызывается button.bind(), а событие on_press ссылается на MainApp.on_press_button().

Этот метод неявно принимает экземпляр виджета, который является самим объектом кнопки. Сообщение будет выводиться на stdout всякий раз при нажатии пользователем на кнопку.

Использование языка дизайна KV

Kivy предоставляет язык дизайна KV, что можно использовать в приложениях Kivy. Язык KV позволяет отделить дизайн интерфейса от логики приложения. Он придерживается принципа разделения ответственности и является частью архитектурного паттерна Модель-Представление-Контроллер (Model-View-Controller).  Предыдущий пример можно обновить, используя язык KV:

from kivy.app import App

from kivy.uix.button import Button

class ButtonApp(App):

    def build(self):

        return Button()

    def on_press_button(self):

        print(‘Вы нажали на кнопку!’)

if __name__ == ‘__main__’:

    app = ButtonApp()

    app.run()

С первого взгляда данный код может показаться несколько странным, так как кнопка Button создается без указания атрибутов или привязывания к ним событий. Здесь Kivy автоматически ищет файл с таким же названием, что и у класса, только строчными буквами и без части App в названии класса.

В данном случае названием класса является ButtonApp, поэтому Kivy будет искать файл button.kv. Если такой файл существует, и он также форматирован должным образом, тогда Kivy использует его при загрузке UI. Попробуйте создать такой файл и добавить следующий код:

<Button>:

    text: ‘Press me’

    size_hint: (.5, .5)

    pos_hint: {‘center_x’: .5, ‘center_y’: .5}

    on_press: app.on_press_button()

Действия каждой строки:

  • Строка 1 соответствует вызову Button в коде Python. Kivy должен осмотреть инициализированный объект для определения кнопки;
  • Строка 2 устанавливает text кнопки;
  • Строка 3 устанавливает ширину и высоту при помощи size_hint;
  • Строка 4 устанавливает позицию кнопки через pos_hint;
  • Строка 5 устанавливает обработчик событий on_press. Для указания Kivy места обработчика событий используется app.on_press_button(). Здесь Kivy будет искать метод .on_press_button() в классе Application.

Вы можете установить все ваши виджеты и лейауты внутри одного или нескольких файлов языка KV. Язык KV также поддерживает импорт модулей Python в KV, создавая динамичные классы, и это далеко не предел. Ознакомиться с полным перечнем его возможностей можно в гиде Kivy по языку KV.

Теперь мы можем приступить к созданию настоящего рабочего приложения.

Создание приложения Kivy Python

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

  • Сложение;
  • Вычитание;
  • Умножение;
  • Деление.

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

Kivy Calculator

Теперь, когда у нас есть в наличии целевой UI, может составить код:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

from kivy.app import App

from kivy.uix.boxlayout import BoxLayout

from kivy.uix.button import Button

from kivy.uix.textinput import TextInput

class MainApp(App):

    def build(self):

        self.operators = [«/», «*», «+», «-«]

        self.last_was_operator = None

        self.last_button = None

        main_layout = BoxLayout(orientation=«vertical»)

        self.solution = TextInput(

            multiline=False, readonly=True, halign=«right», font_size=55

        )

        main_layout.add_widget(self.solution)

        buttons = [

            [«7», «8», «9», «/»],

            [«4», «5», «6», «*»],

            [«1», «2», «3», «-«],

            [«.», «0», «C», «+»],

        ]

        for row in buttons:

            h_layout = BoxLayout()

            for label in row:

                button = Button(

                    text=label,

                    pos_hint={«center_x»: 0.5, «center_y»: 0.5},

                )

                button.bind(on_press=self.on_button_press)

                h_layout.add_widget(button)

            main_layout.add_widget(h_layout)

        equals_button = Button(

            text=«=», pos_hint={«center_x»: 0.5, «center_y»: 0.5}

        )

        equals_button.bind(on_press=self.on_solution)

        main_layout.add_widget(equals_button)

        return main_layout

Калькулятор работает следующим образом:

  • В строках с 8 по 10 создается список operators и несколько полезных значений, last_was_operator и last_button, которые будут использованы чуть позже.
  • В строках с 11 по 15 создается лейаут верхнего уровня main_layout, к нему также добавляется виджет только для чтения TextInput.
  • В строках с 16 по 21 создается вложенный список из списков, где есть большая часть кнопок для калькулятора.
  • В строке 22 начинается цикл for для кнопок. Для каждого вложенного списка делается следующее:
    1. В строке 23 создается BoxLayout с горизонтальной ориентацией.
    2. В строке 24 начинается еще один цикл for для элементов вложенного списка.
    3. В строках с 25 по 39 создаются кнопки для ряда и связываются обработчиком событий, после чего кнопки добавляются к горизонтальному BoxLayout из строки 23.
    4. В строке 31 этот лейаут добавляется к main_layout.
  • В строках с 33 по 37 создается кнопка равно (=) и привязывается к обработчику событий, после чего она добавляется к main_layout.

Далее создается обработчик событий .on_button_press(). Код будет выглядеть следующим образом:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

def on_button_press(self, instance):

    current = self.solution.text

    button_text = instance.text

    if button_text == «C»:

        # Очистка виджета с решением

        self.solution.text = «»

    else:

        if current and (

            self.last_was_operator and button_text in self.operators):

            # Не добавляйте два оператора подряд, рядом друг с другом

            return

        elif current == «» and button_text in self.operators:

            # Первый символ не может быть оператором

            return

        else:

            new_text = current + button_text

            self.solution.text = new_text

    self.last_button = button_text

    self.last_was_operator = self.last_button in self.operators

Почти все виджеты приложения вызывают .on_button_press(). Это работает следующим образом:

  • Строка 41 принимает аргумент instance, в результате чего можно узнать, какой виджет вызвал функцию.
  • Строки между 42 и 43 извлекают и хранят значения solution и text кнопки.
  • Строки c 45 по 47 проверяют, на какую кнопку нажали. Если пользователь нажимает с, тогда очищается solution. В противном случае используется утверждение else.
  • Строка 49 проверяет, было ли у решения предыдущее значение.
  • Строки с 50 по 52 проверяют, была ли последняя нажатая кнопка оператором. Если да, тогда solution обновляться не будет. Это необходимо для предотвращения создания двух операций в одном ряду. К примеру, 1 * / будет недействительным утверждением.
  • Строки с 53 по 55 проверяют, является ли первый символ оператором. Если да, тогда solution обновляться не будет, так как первое значение не может быть значением оператора.
  • Строки с 56 по 58 переходят к условию else. Если никакое из предыдущих значений не найдено, тогда обновляется solution.
  • Строка 59 устанавливает last_button к метке последней нажатой кнопки.
  • Строка 60 устанавливает last_was_operator к значению True или False в зависимости от того, был символ оператором или нет.

Последней частью кода будет .on_solution():

def on_solution(self, instance):

    text = self.solution.text

    if text:

        solution = str(eval(self.solution.text))

        self.solution.text = solution

Здесь берется текущий текст из solution и используется встроенный в Python eval() для исполнения. Если пользователь создал формулу вроде 1+2, тогда eval() запустит код и вернет результат. В конце результат устанавливается как новое значение виджета solution.

На заметку: порой eval() бывает опасным, так как он может запустить произвольный код. Многие разработчики избегают его использование именно по этой причине. Тем не менее, ввиду задействования только целых чисел, операторов и точки в качестве вводных данных для eval(), в данном контексте его можно использовать безопасно.

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

KV Calculator

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

from kivy.app import App

from kivy.uix.boxlayout import BoxLayout

from kivy.uix.button import Button

from kivy.uix.textinput import TextInput

class MainApp(App):

    def build(self):

        self.operators = [«/», «*», «+», «-«]

        self.last_was_operator = None

        self.last_button = None

        main_layout = BoxLayout(orientation=«vertical»)

        self.solution = TextInput(

            multiline=False, readonly=True, halign=«right», font_size=55

        )

        main_layout.add_widget(self.solution)

        buttons = [

            [«7», «8», «9», «/»],

            [«4», «5», «6», «*»],

            [«1», «2», «3», «-«],

            [«.», «0», «C», «+»],

        ]

        for row in buttons:

            h_layout = BoxLayout()

            for label in row:

                button = Button(

                    text=label,

                    pos_hint={«center_x»: 0.5, «center_y»: 0.5},

                )

                button.bind(on_press=self.on_button_press)

                h_layout.add_widget(button)

            main_layout.add_widget(h_layout)

        equals_button = Button(

            text=«=», pos_hint={«center_x»: 0.5, «center_y»: 0.5}

        )

        equals_button.bind(on_press=self.on_solution)

        main_layout.add_widget(equals_button)

        return main_layout

    def on_button_press(self, instance):

        current = self.solution.text

        button_text = instance.text

        if button_text == «C»:

            # Очистка виджета с решением

            self.solution.text = «»

        else:

            if current and (

                self.last_was_operator and button_text in self.operators):

                # Не добавляйте два оператора подряд, рядом друг с другом

                return

            elif current == «» and button_text in self.operators:

                # Первый символ не может быть оператором

                return

            else:

                new_text = current + button_text

                self.solution.text = new_text

        self.last_button = button_text

        self.last_was_operator = self.last_button in self.operators

    def on_solution(self, instance):

        text = self.solution.text

        if text:

            solution = str(eval(self.solution.text))

            self.solution.text = solution

if __name__ == «__main__»:

    app = MainApp()

    app.run()

Пришло время разместить приложение в Google Play или в AppStore!

По завершении составления кода вы можете поделиться своим приложением с другими. Хорошим способом сделать это может стать превращение вашего кода в приложения для смартфона на Android. Для этого вначале нужно установить пакет buildozer через pip:

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

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

[app]

# (str) Название вашего приложения

title = KvCalc

# (str) Название упаковки

package.name = kvcalc

# (str) Домен упаковки (нужен для упаковки android/ios)

package.domain = org.kvcalc

Не бойтесь посмотреть оставшуюся часть файла для выяснения того, что еще можно поменять.

На данный момент приложение почти готово к сборке, однако для начала нужно установить зависимости для buildozer.  После их установки скопируйте ваше приложение калькулятора в новую папку и переименуйте его в main.py. Этого требует buildozer. Если файл будет назван неверно, тогда процесс сборки завершится неудачей.

Теперь можно запустить следующую команду:

$ buildozer v android debug

Этап сборки займет время! На моем компьютере на это ушло около 15-20 минут. Здесь все зависит от вашего железа, так что времени может потребоваться еще больше. Расслабьтесь, налейте чашечку кофе или прогуляйтесь. Buildozer скачает те элементы Android SDK, которые нужны для процесса сборки. Если все идет по плану, тогда в папке bin появится файл под названием, напоминающим что-то вроде kvcalc-0.1-debug.apk.

Далее требуется связать телефон Android с компьютером и перенести туда файл apk. Затем откройте менеджер файлов телефона и кликните на файл apk. Android должен спросить, хотите ли вы установить приложение. Есть вероятность появления предупреждения, ведь приложение было скачано не из Google Play. Тем не менее, вы по-прежнему сможете установить его.

Вот как выглядит калькулятор, запущенный на Samsung S9:

KV Calc Android

У buildozer также есть несколько других команд, которые вы можете использовать. Изучите документацию, чтобы подробнее узнать об этом.

При необходимости добиться более детального управления упаковку можно осуществить через python-for-android. Здесь это обсуждаться не будет, но если интересно, ознакомьтесь, как еще можно быстро начать проект.

Создание приложений для iPhone (iOS) на Python

Инструкция для сборки приложения для iOS будет немного сложнее, нежели для Android. Для получения последней информации всегда проверяйте обновления официальной документации Kivy.

Вам нужен будет компьютер с операционной системой OS X: MacBook или iMac. На Linux или Windows вы не сможете создать приложения для Apple.

Перед упаковкой приложения для iOS на Mac необходимо выполнить следующие команды:

$ brew install autoconf automake libtool pkgconfig

$ brew link libtool

$ sudo easy_install pip

$ sudo pip install Cython==0.29.10

После успешной установки нужно скомпилировать при использования следующих команд:

$ git clone git://github.com/kivy/kivyios

$ cd kivyios

$ ./toolchain.py build python3 kivy

Если вы получаете ошибку, где говорится, что iphonesimulator не найден, тогда поищите способ решение проблемы на StackOverflow, после чего попробуйте запустить команды вновь.

Если вы получаете ошибки SSL, тогда скорее всего у вас не установлен OpenSSL от Python. Следующая команда должна это исправить:

$ cd /Applications/Python 3.7/

$ ./Install Certificates.command

Теперь вернитесь назад и запустите команду toolchain опять.

После успешного выполнения всех указанных выше команд можете создать проект Xcode при помощи использования скрипта toolchain. Перед созданием проекта Xcode переименуйте ваше главное приложение в main.py, это важно. Выполните следующую команду.

./toolchain.py create <title> <app_directory>

Здесь должна быть папка под названием title, внутри которой будет проект Xcode. Теперь можно открыть проект Xcode и работать над ним отсюда. Обратите внимание, что если вы хотите разместить свое приложение на AppStore, вам понадобится создать аккаунт разработчика на developer.apple.com и заплатить годовой взнос.

Создание exe приложений для Windows на Python используя Kivy

Упаковать приложение Kivy для Windows можно при помощи PyInstaller. Если ранее вы никогда не работали с ним, тогда изучите тему использования PyInstaller для упаковки кода Python в исполняемый файл.

Для установки PyInstaller можно использовать pip:

$ pip install pyinstaller

Следующая команда упакует ваше приложение:

Команда создаст исполняемый файл Windows, а вместе с ним еще несколько других файлов. Аргумент -w говорит PyInstaller, что приложение открывается в оконном режиме и не является приложение для командной строки. Если вы хотите, чтобы PyInstaller создал только один исполняемый файл, тогда можете передать в дополнение к -w аргумент --onefile.

Создание приложений для macOS на Python используя Kivy

Как и в случае с Windows, для создания исполняемого файла Mac можно также использовать PyInstaller. Единственным условием является запуск следующей команды на Mac:

$ pyinstaller main.py w onefile

Результатом станет один исполняемый файл в папке dist. Название исполняемого файла будет таким же, как и название файла Python, что был передан PyInstaller.

Если вы хотите уменьшить размер исполняемого файла или использовать в приложении GStreamer, тогда для получения дополнительной информации изучите тему упаковки для macOS.

Заключение

Kivy является действительно интересным фреймворком GUI, что можно использовать для создания пользовательских интерфейсов и мобильных приложений для Android и iOS. Внешне приложения Kivy будут отличаться от нативных приложений выбранной платформы. В том случае, если вы хотите выделяться на фоне конкурентов, это может быть выгодным преимуществом.

В данном руководстве были рассмотрены основы Kivy, среди которых стоит выделить добавление виджетов, привязку событий, планировку виджетов и лейауты, а также использование языка KV. В результате мы получили рабочее приложение Kivy и рассмотрели способы его переноса на другие платформы, в том числе мобильные.

В Kivy есть множество виджетов и концептов, которые не были рассмотрены в статьи. Для дальнейшего изучения темы можете изучить официальный сайт Kivy, где размещены разнообразные руководства, примеры приложений и многое другое.

Рекомендации

Для дальнейшего изучения Kivy ознакомьтесь со следующими ресурсами:

  • Гид программирования на Kivy 
  • Документация по упаковке приложений Kivy
  • Сборка приложений GUI через Python

Чтобы посмотреть, как создать приложение с графическим интерфейсом при использовании другого GUI фреймфорка Python, можете ознакомиться со статьями о wxPython.

Являюсь администратором нескольких порталов по обучению языков программирования Python, Golang и Kotlin. В составе небольшой команды единомышленников, мы занимаемся популяризацией языков программирования на русскоязычную аудиторию. Большая часть статей была адаптирована нами на русский язык и распространяется бесплатно.

E-mail: vasile.buldumac@ati.utm.md

Образование
Universitatea Tehnică a Moldovei (utm.md)

  • 2014 — 2018 Технический Университет Молдовы, ИТ-Инженер. Тема дипломной работы «Автоматизация покупки и продажи криптовалюты используя технический анализ»
  • 2018 — 2020 Технический Университет Молдовы, Магистр, Магистерская диссертация «Идентификация человека в киберпространстве по фотографии лица»

замечания

Kivy — это библиотека Python с открытым исходным кодом для быстрой разработки межплатформенных пользовательских интерфейсов. Приложения Kivy могут быть разработаны для Linux, Windows, OS X, Android и iOS с использованием той же кодовой базы.

Графика создается через OpenGL ES 2, а не через собственные виджеты, что приводит к довольно равномерному появлению в разных операционных системах.

Разработка интерфейсов в Kivy необязательно включает использование kvlang, небольшого языка, который поддерживает выражения, подобные python, и взаимодействие python. Использование kvlang может значительно упростить разработку пользовательского интерфейса по сравнению с использованием исключительно Python.

Kivy может свободно пользоваться (в настоящее время под лицензией MIT) и профессионально поддерживаться.

Установка и настройка

Windows

Есть два варианта установки Kivy:

Сначала убедитесь, что инструменты python обновлены.

python -m pip install --upgrade pip wheel setuptools

Затем установите основные зависимости.

python -m pip install docutils pygments pypiwin32 kivy.deps.sdl2 kivy.deps.glew

Хотя у Kivy уже есть поставщики аудио и видео, GStreamer требуется для более продвинутых материалов.

python -m pip install kivy.deps.gstreamer --extra-index-url https://kivy.org/downloads/packages/simple/

Чтобы упростить, <python> в следующем тексте означает путь к каталогу с файлом python.exe .

  1. Рулевое колесо

    Колесный пакет предоставляет скомпилированный Kivy, но с удаленными cython источника cython , что означает, что основной код нельзя перекомпилировать с помощью этого способа. Код Python, однако, доступен для редактирования.

    Стабильная версия Kivy доступна на pypi.

    python -m pip install kivy
    

    Последняя версия официального репозитория доступна через ночные колеса, доступные на диске Google. Перейдите по ссылке в документах, соответствующих вашей версии python. После загрузки правильного колеса переименуйте его в соответствии с форматированием этого примера и запустите команду.

    python -m pip install C:Kivy-1.9.1.dev-cp27-none-win_amd64.whl
    
  2. Источник

    Для установки Kivy из источника требуется больше требуемых зависимостей, чем использование колес, но установка более гибкая.

    Создайте новый файл в <python>Libdistutilsdistutils.cfg с этими строками, чтобы обеспечить правильный компилятор для исходного кода.

    [build]
    compiler = mingw32
    

    Тогда нужен компилятор. Либо используйте некоторые, которые вы уже установили, либо загрузите mingwpy . Важные файлы, такие как gcc.exe будут расположены в <python>Scripts .

    python -m pip install -i https://pypi.anaconda.org/carlkl/simple mingwpy
    

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

    set USE_SDL2=1
    set USE_GSTREAMER=1
    

    Теперь установите дополнительные зависимости, необходимые для компиляции.

    python -m pip install cython kivy.deps.glew_dev kivy.deps.sdl2_dev
    python -m pip install kivy.deps.gstreamer_dev --extra-index-url https://kivy.org/downloads/packages/simple/
    

    Check Paths чтобы убедиться, что все установлено правильно и установите Kivy. Выберите один из следующих вариантов:

    python -m pip install C:master.zip
    python -m pip install https://github.com/kivy/kivy/archive/master.zip
    

пути

Kivy нуждается в доступе к двоичным файлам из некоторых зависимостей. Это означает, что правильные папки должны находиться в PATH среды.

set PATH=<python>Tools;<python>Scripts;<python>sharesdl2bin;%PATH%

Таким образом, <python>Libidlelib; Python может быть включен в путь с помощью <python>Libidlelib; , Затем запустите idle в консоли, а IDLE будет готово к использованию Kivy.

Упростите это

Чтобы избежать повторной установки переменных среды, либо задайте каждый необходимый путь таким образом, либо создайте пакетный ( .bat ) файл с этими строками, помещенными в <python> :

set PATH=%~dp0;%~dp0Tools;%~dp0Scripts;%~dp0sharesdl2bin;%~dp0Libidlelib;%PATH%
cmd.exe

Чтобы запустить проект Kivy после установки, запустите cmd.exe или пакетный файл и используйте python <filename>.py

установка на Ubuntu

Для установки kivy на ubuntu с помощью kivy example open terminal и выполните следующую команду

Сначала добавьте ppa

 sudo add-apt-repository ppa:kivy-team/kivy

Для установки kivy

 sudo apt-get install python-kivy

Для установки примеров kivy

 sudo apt-get install python-kivy-example

Прикоснитесь, захватите и переместите

В следующем примере создается холст с 2 точками и 1 строка между ними. Вы сможете перемещать точку и линию вокруг.

from kivy.app import App
from kivy.graphics import Ellipse, Line
from kivy.uix.boxlayout import BoxLayout


class CustomLayout(BoxLayout):

    def __init__(self, **kwargs):
        super(CustomLayout, self).__init__(**kwargs)

        self.canvas_edge = {}
        self.canvas_nodes = {}
        self.nodesize = [25, 25]

        self.grabbed = {}

        #declare a canvas
        with self.canvas.after:
            pass

        self.define_nodes()
        self.canvas.add(self.canvas_nodes[0])
        self.canvas.add(self.canvas_nodes[1])
        self.define_edge()
        self.canvas.add(self.canvas_edge)
    

    def define_nodes(self):
        """define all the node canvas elements as a list"""

        self.canvas_nodes[0] = Ellipse(
            size = self.nodesize,
            pos =  [100,100]
            )

        self.canvas_nodes[1] = Ellipse(
            size = self.nodesize,
            pos =  [200,200]
            )

    def define_edge(self):
        """define an edge canvas elements"""


        self.canvas_edge = Line(
            points =  [
                self.canvas_nodes[0].pos[0] + self.nodesize[0] / 2,
                self.canvas_nodes[0].pos[1] + self.nodesize[1] / 2,
                self.canvas_nodes[1].pos[0] + self.nodesize[0] / 2,
                self.canvas_nodes[1].pos[1] + self.nodesize[1] / 2
                ],
            joint = 'round',
            cap = 'round',
            width = 3
            )


    def on_touch_down(self, touch):

        for key, value in self.canvas_nodes.items():
            if (value.pos[0] - self.nodesize[0]) <= touch.pos[0] <= (value.pos[0] + self.nodesize[0]):
                if (value.pos[1] - self.nodesize[1]) <= touch.pos[1] <= (value.pos[1] + self.nodesize[1]):
                    touch.grab(self)
                    self.grabbed = self.canvas_nodes[key]
                    return True

    def on_touch_move(self, touch):

        if touch.grab_current is self:
            self.grabbed.pos = [touch.pos[0] - self.nodesize[0] / 2, touch.pos[1] - self.nodesize[1] / 2]
            self.canvas.clear()
            self.canvas.add(self.canvas_nodes[0])
            self.canvas.add(self.canvas_nodes[1])
            self.define_edge()
            self.canvas.add(self.canvas_edge)
        else:
            # it's a normal touch
            pass

    def on_touch_up(self, touch):
        if touch.grab_current is self:
            # I receive my grabbed touch, I must ungrab it!
            touch.ungrab(self)
        else:
            # it's a normal touch
            pass

class MainApp(App):

    def build(self):
        root = CustomLayout()
        return root

if __name__ == '__main__':
    MainApp().run()

Привет, мир в киви.

Следующий код иллюстрирует, как сделать приложение «hello world» в kivy. Чтобы запустить это приложение в ios и android, сохраните его как main.py и используйте buildozer.

from kivy.app import App
from kivy.uix.label import Label
from kivy.lang import Builder

Builder.load_string('''
<SimpleLabel>:
    text: 'Hello World'
''')


class SimpleLabel(Label):
    pass


class SampleApp(App):
    def build(self):
        return SimpleLabel()

if __name__ == "__main__":
    SampleApp().run()

Простой пример в Киви.

Следующий код иллюстрирует, как делать простые всплывающие окна с Kivy.

from kivy.app import App
from kivy.uix.popup import Popup
from kivy.lang import Builder
from kivy.uix.button import Button

Builder.load_string('''
<SimpleButton>:
    on_press: self.fire_popup()
<SimplePopup>:
    id:pop
    size_hint: .4, .4
    auto_dismiss: False
    title: 'Hello world!!'
    Button:
        text: 'Click here to dismiss'
        on_press: pop.dismiss()
''')


class SimplePopup(Popup):
    pass

class SimpleButton(Button):
    text = "Fire Popup !"
    def fire_popup(self):
        pops=SimplePopup()
        pops.open()

class SampleApp(App):
    def build(self):
        return SimpleButton()

SampleApp().run()

RecycleView

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.button import Button


items = [
    {"color":(1, 1, 1, 1), "font_size": "20sp", "text": "white",     "input_data": ["some","random","data"]},
    {"color":(.5,1, 1, 1), "font_size": "30sp", "text": "lightblue", "input_data": [1,6,3]},
    {"color":(.5,.5,1, 1), "font_size": "40sp", "text": "blue",      "input_data": [64,16,9]},
    {"color":(.5,.5,.5,1), "font_size": "70sp", "text": "gray",      "input_data": [8766,13,6]},
    {"color":(1,.5,.5, 1), "font_size": "60sp", "text": "orange",    "input_data": [9,4,6]},
    {"color":(1, 1,.5, 1), "font_size": "50sp", "text": "yellow",    "input_data": [852,958,123]}
]


class MyButton(Button):

    def print_data(self,data):
        print(data)


KV = '''

<MyButton>:
    on_release:
        root.print_data(self.input_data)

RecycleView:
    data: []
    viewclass: 'MyButton'
    RecycleBoxLayout:
        default_size_hint: 1, None
        orientation: 'vertical'

'''


class Test(App):
    def build(self):
        root = Builder.load_string(KV)
        root.data = [item for item in items]
        return root


Test().run()

Различные способы запуска простого приложения и взаимодействия с виджетами

Большинство приложений kivy начинаются с этой структуры:

from kivy.app import App

class TutorialApp(App):
    def build(self):
        return 
TutorialApp().run()

Существует несколько способов:

Все коды, приведенные ниже (кроме примеров 1 и 3), имеют один и тот же виджетов и аналогичные функции, но показывают другой способ создания приложения.

Пример 1: возврат одного виджета (простого приложения Hello World)

from kivy.app import App
from kivy.uix.button import Button
class TutorialApp(App):
    def build(self):
        return Button(text="Hello World!")
TutorialApp().run()

Пример 2: возврат нескольких виджетов + кнопка печатает текст метки

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button

class TutorialApp(App):
    def build(self):
        mylayout = BoxLayout(orientation="vertical")
        mylabel = Label(text= "My App")
        mybutton =Button(text="Click me!")  
        mylayout.add_widget(mylabel)
        mybutton.bind(on_press= lambda a:print(mylabel.text))
        mylayout.add_widget(mybutton)
        return mylayout
TutorialApp().run()

Пример 3: использование класса (одиночный виджет) + кнопка печатает «Моя кнопка»

from kivy.app import App
from kivy.uix.button import Button

class Mybutton(Button):
    text="Click me!"
    on_press =lambda a : print("My Button")    
    
class TutorialApp(App):
    def build(self):
        return Mybutton()
TutorialApp().run()

Пример 4: это то же самое, что и ex. 2, но он показывает, как использовать класс

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button

class MyLayout(BoxLayout):
    #You don't need to understand these 2 lines to make it work!
    def __init__(self, **kwargs):
        super(MyLayout, self).__init__(**kwargs)
        
        self.orientation="vertical"
        mylabel = Label(text= "My App")
        self.add_widget(mylabel)
        mybutton =Button(text="Click me!")
        mybutton.bind(on_press= lambda a:print(mylabel.text))
        self.add_widget(mybutton)
        
class TutorialApp(App):
    def build(self):
        return MyLayout()
TutorialApp().run()

С языком .kv

Пример 5: то же самое, но показывая, как использовать язык kv в python

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout 
# BoxLayout: it's in the python part, so you need to import it

from kivy.lang import Builder
Builder.load_string("""
<MyLayout>
    orientation:"vertical"
    Label: # it's in the kv part, so no need to import it
        id:mylabel
        text:"My App"
    Button:
        text: "Click me!"
        on_press: print(mylabel.text)
""")
class MyLayout(BoxLayout):
    pass
class TutorialApp(App):
    def build(self):
        return MyLayout()
TutorialApp().run()

** Пример 6: то же самое с частью kv в файле Tutorial.kv **

В .py:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout

class MyLayout(BoxLayout):
    pass
class TutorialApp(App):  
#the kv file name will be Tutorial (name is before the "App")
    def build(self):
        return MyLayout()
TutorialApp().run()

В Tutorial.kv:

<MyLayout> # no need to import stuff in kv!
    orientation:"vertical"
    Label:
        id:mylabel
        text:"My App"
    Button:
        text: "Click me!"
        on_press: print(mylabel.text)

** Пример 7: ссылка на конкретный файл kv + a def в python, получающий label.text **

В .py:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout

class MyLayout(BoxLayout):
    def printMe(self_xx, yy):
        print(yy)
class TutorialApp(App): 
    def build(self):
        self.load_kv('myapp.kv')
        return MyLayout()
TutorialApp().run()

В myapp.kv: ориентация: «вертикальная» Ярлык: id: mylabel text: кнопка «Мое приложение»: текст: «Нажмите меня!» on_press: root.printMe (mylabel.text)

Пример 8: кнопка печатает текст метки (с помощью def в python с использованием ids («ID»))

Заметить, что:

  • self_xx из примера 7 заменяется на self

В .py:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout

class MyLayout(BoxLayout):
    def printMe(self):
        print(self.ids.mylabel.text)
class TutorialApp(App):
    def build(self):
        self.load_kv('myapp.kv')
        return MyLayout()
TutorialApp().run()

В myapp.kv:

<MyLayout>
    orientation:"vertical"
    Label:
        id:mylabel
        text:"My App"
    Button:
        text: "Click me!"
        on_press: root.printMe()

Пример 9: кнопка печатает текст метки (с помощью def в python с использованием StringProperty)

В .py:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty
class MyLayout(BoxLayout):
    stringProperty_mylabel= StringProperty("My App")
    def printMe(self):
        print(self.stringProperty_mylabel)

class TutorialApp(App):
    def build(self):
        return MyLayout()
TutorialApp().run()

В Tutorial.kv:

<MyLayout>
    orientation:"vertical"
    Label:
        id:mylabel
        text:root.stringProperty_mylabel
    Button:
        text: "Click me!"
        on_press: root.printMe()

Пример 10: кнопка печатает текст метки (с помощью def в python с использованием ObjectProperty)

В .py:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
class MyLayout(BoxLayout):
    objectProperty_mylabel= ObjectProperty(None)
    def printMe(self):
        print(self.objectProperty_mylabel.text)

class TutorialApp(App):
    def build(self):
        return MyLayout()
TutorialApp().run()

В Tutorial.kv:

<MyLayout>
    orientation:"vertical"
    objectProperty_mylabel:mylabel
    Label:
        id:mylabel
        text:"My App"
    Button:
        text: "Click me!"
        on_press: root.printMe()

Понравилась статья? Поделить с друзьями:
  • Установка joomla на хостинг инструкция
  • Установка hive os на ssd инструкция
  • Установка dis v57 bmw полная инструкция
  • Установка 16 клапанного двигателя на ваз 2107 пошаговая инструкция
  • Установить эцп на компьютер с флешки пошаговая инструкция