- Installation on macOS¶
- Installation components¶
- Installing Python¶
- Homebrew¶
- MacPorts¶
- Frameworks¶
- Source installation Dependencies¶
- Using The Kivy.app¶
- Using the App Virtual environment¶
- Start any Kivy Application¶
- Kivy — Создание мобильных приложений на Python
- Принципы работы фреймворка Kivy Python
- Установка Kivy
- Creating packages for macOS¶
- Using the Kivy SDK¶
- Using Buildozer¶
- Using PyInstaller and Homebrew¶
- Complete guide¶
- Editing the spec file¶
- Build the spec and create a DMG¶
- Additional Libraries¶
- GStreamer¶
- Using PyInstaller without Homebrew¶
Installation on macOS¶
To install Kivy on macOS using pip , please follow the main installation guide . Otherwise, continue to the Kivy.app instructions below .
Installation components¶
Following, are additional information linked to from some of the steps in the main installation guide , specific to macOS.
Installing Python¶
Homebrew¶
If you’re using Homebrew, you can install Python with:
MacPorts¶
If you’re using Macports, you can install Python with:
# Install and set e.g. Python 3.8 as the default port install python38 port select --set python python38 # Install and set pip as the default:: port install py38-pip port select --set pip py38-pip
Frameworks¶
To install frameworks Python on macOS, download it from the main Python website and follow the installation steps. You can read more about the installation in the Python guide.
Source installation Dependencies¶
To install Kivy from source, please follow the installation guide until you reach the Kivy install step and then install the additional dependencies below before continuing.
pkg-config is required to build Kivy from source. If you’re using brew as your package manager, you can install it with:
Now that you have all the dependencies for kivy, you need to make sure you have the command line tools installed:
Using The Kivy.app¶
Kivy.app is built with MACOSX_DEPLOYMENT_TARGET=10.9 .
You can find complete instructions to build and package apps with Kivy.app in the readme of the kivy-sdk-packager repo.
To install the Kivy virtualenv, you must:
- Navigate to the latest Kivy release on Kivy’s website or GitHub and download Kivy.dmg . You can also download a nightly snapshot of Kivy.app.
- Open the dmg
- In the GUI copy the Kivy.app to /Applications by dragging the folder icon to the right.
- Optionally create a symlink by running the following command:
ln -s /Applications/Kivy.app/Contents/Resources/script /usr/local/bin/kivy
Using the App Virtual environment¶
The path to the underlying virtualenv is /Applications/Kivy.app/Contents/Resources/venv . To activate it so you can use python, like any normal virtualenv, do:
pushd /Applications/Kivy.app/Contents/Resources/venv/bin source activate source kivy_activate popd
On the default mac (zsh) shell you must be in the bin directory containing activate to be able to activate the virtualenv, hence why we changed the directory temporarily.
kivy_activate sets up the environment to be able to run Kivy, by setting the kivy home, and other variables.
Start any Kivy Application¶
You can run any Kivy application by simply dragging the application’s main file onto the Kivy.app icon.
Kivy — Создание мобильных приложений на Python
В наши дни каждый разработчик может столкнуться с необходимостью работы над мобильным или веб-приложением на Python. В Python нет встроенных инструментов для мобильных устройств, тем не менее существуют пакеты, которые можно использовать для создания мобильных приложений. Это Kivy, PyQt и даже библиотека Toga от Beeware.
Библиотеки являются основными элементами мобильного мира 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 создается следующим образом:
Creating packages for macOS¶
This guide describes multiple ways for packaging Kivy applications. Packaging using the Kivy SDK is recommended for general use.
Using the Kivy SDK¶
These instructions apply only from Kivy v2.0.0 onwards.
Kivy.app is built with MACOSX_DEPLOYMENT_TARGET=10.9 .
We provide a Kivy DMG with all dependencies bundled in a virtual environment, including a Python interpreter that can be used as a base to package kivy apps.
This is the safest approach because it packages the binaries without references to any binaries on the system on which the app is packaged. Because all references are to frameworks included in the dmg or to binaries with the dmg. As opposed to e.g. pyinstaller which copies binaries from your local python installation.
You can find complete instructions to build and package apps with Kivy.app, starting either with Kivy.app or building from scratch, in the readme of the kivy-sdk-packager repo.
Using Buildozer¶
pip install git+http://github.com/kivy/buildozer cd /to/where/I/Want/to/package buildozer init
Edit the buildozer.spec and add the details for your app. Dependencies can be added to the requirements= section.
By default the kivy version specified in the requirements is ignored.
If you have a Kivy.app at /Applications/Kivy.app then that is used, for packaging. Otherwise the latest build from kivy.org using Kivy master will be downloaded and used.
When you’re ready to package your macOS app just run:
Once the app is packaged, you might want to remove unneeded packages, just reduce the package to its minimal state that is needed for the app to run.
Buildozer right now uses the Kivy SDK to package your app. If you want to control more details about your app than buildozer currently offers then you can use the SDK directly, as detailed in the section below.
Using PyInstaller and Homebrew¶
Package your app on the oldest macOS version you want to support.
Complete guide¶
$ brew reinstall --build-from-source sdl2 sdl2_image sdl2_ttf sdl2_mixer
Note If your project depends on GStreamer or other additional libraries (re)install them with —build-from-source as described below.
$ pip install Cython==0.29.33 $ pip install -U kivy
$ pip install -U pyinstaller
$ pyinstaller -y --clean --windowed --name touchtracer \ --exclude-module _tkinter \ --exclude-module Tkinter \ --exclude-module enchant \ --exclude-module twisted \ /usr/local/share/kivy-examples/demo/touchtracer/main.py
Note This will not yet copy additional image or sound files. You would need to adapt the created .spec file for that.
Editing the spec file¶
The specs file is named touchtracer.spec and is located in the directory where you ran the pyinstaller command.
You need to change the COLLECT() call to add the data of touchtracer ( touchtracer.kv , particle.png , …). Change the line to add a Tree() object. This Tree will search and add every file found in the touchtracer directory to your final package. Your COLLECT section should look something like this:
coll = COLLECT(exe, Tree('/usr/local/share/kivy-examples/demo/touchtracer/'), a.binaries, a.zipfiles, a.datas, strip=None, upx=True, name='touchtracer')
This will add the required hooks so that PyInstaller gets the required Kivy files. We are done. Your spec is ready to be executed.
Build the spec and create a DMG¶
$ pyinstaller -y --clean --windowed touchtracer.spec
$ pushd dist $ hdiutil create ./Touchtracer.dmg -srcfolder touchtracer.app -ov $ popd
Additional Libraries¶
GStreamer¶
If your project depends on GStreamer:
$ brew reinstall —build-from-source gstreamer gst-plugins-
If your Project needs Ogg Vorbis support be sure to add the —with-libvorbis option to the command above.
If you are using Python from Homebrew you will also need the following step until this pull request gets merged:
$ brew reinstall --with-python --build-from-source https://github.com/cbenhagen/homebrew/raw/patch-3/Library/Formula/gst-python.rb
Using PyInstaller without Homebrew¶
First install Kivy and its dependencies without using Homebrew as mentioned here http://kivy.org/docs/installation/installation.html#development-version.
Once you have kivy and its deps installed, you need to install PyInstaller.
Let’s assume we use a folder like testpackaging :
cd testpackaging git clone http://github.com/pyinstaller/pyinstaller
Create a file named touchtracer.spec in this directory and add the following code to it:
# -*- mode: python -*- block_cipher = None from kivy.tools.packaging.pyinstaller_hooks import get_deps_all, hookspath, runtime_hooks a = Analysis(['/path/to/yout/folder/containing/examples/demo/touchtracer/main.py'], pathex=['/path/to/yout/folder/containing/testpackaging'], binaries=None, win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, hookspath=hookspath(), runtime_hooks=runtime_hooks(), **get_deps_all()) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, exclude_binaries=True, name='touchtracer', debug=False, strip=False, upx=True, console=False ) coll = COLLECT(exe, Tree('../kivy/examples/demo/touchtracer/'), Tree('/Library/Frameworks/SDL2_ttf.framework/Versions/A/Frameworks/FreeType.framework'), a.binaries, a.zipfiles, a.datas, strip=False, upx=True, name='touchtracer') app = BUNDLE(coll, name='touchtracer.app', icon=None, bundle_identifier=None)
Change the paths with your relevant paths:
a = Analysis(['/path/to/yout/folder/containing/examples/demo/touchtracer/main.py'], pathex=['/path/to/yout/folder/containing/testpackaging'], . . coll = COLLECT(exe, Tree('../kivy/examples/demo/touchtracer/'),
Then run the following command:
pyinstaller/pyinstaller.py touchtracer.spec
Replace touchtracer with your app where appropriate. This will give you a .app in the dist/ folder.