当前位置:   article > 正文

python-22-使用Kivy开发手机app

kivy

最新 python Kivy打包 App(p4a)方法
【异常】has been compiled by a more recent version of the Java Runtime (class file version 55.0)
Android NDK 各版本下载地址大全
Python Kivy打包成安卓App
使用 Python + Kivy 编写和打包安卓APP
Buildozer doesn’t install hostpython3
armeabi-v7a arm64-v8a armeabi x86 x86_64区别
基于Python的跨平台应用程序界面设计工具:Kivy Designer为你打造极致UI体验

在这里插入图片描述

1 安装测试kivy

1.1 pip配置加速

1.首先建立.pip.conf文件
mkdir ~/.pip
vim ~/.pip/pip.conf

2.写入源
[global]
timeout = 6000
index-url = http://mirrors.aliyun.com/pypi/simple/
trusted-host = mirrors.aliyun.com

3.国内一些源
阿里云 http://mirrors.aliyun.com/pypi/simple/
中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/
豆瓣(douban) http://pypi.douban.com/simple/
清华大学 https://pypi.tuna.tsinghua.edu.cn/simple/
中国科学技术大学 http://pypi.mirrors.ustc.edu.cn/simple/

4.安装kivy
CMD>conda create -n python3106 python=3.10.6
CMD>conda activate python3106
CMD>pip install kivy
CMD>pip install kivy_examples
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

1.2 应用示例

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

class TestApp(App):
    def build(self):
        return Button(text='Hello,kivy')

TestApp().run()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

运行后输出
在这里插入图片描述

在这里插入图片描述

2 使用p4a打包apk【各种小问题】

前提:ubuntu系统(物理机或使用VirtualBox安装的虚拟机)。
版本:ubuntu 22.04

2.1 安装工具

python-for-android:以下简称p4a,是Kivy官方推荐的打包方式。

2.1.1 安装p4a

(1)安装p4a的依赖
网址https://python-for-android.readthedocs.io/en/latest/quickstart/查看依赖。

sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install build-essential ccache git zlib1g-dev python3 python3-dev libncurses5:i386 libstdc++6:i386 zlib1g:i386  unzip ant ccache autoconf libtool libssl-dev
  • 1
  • 2
  • 3

上面的命令如果出现Package … is not configured yet.的报错,解决方法如下:

sudo mv /var/lib/dpkg/info/ /var/lib/dpkg/info_old/
sudo mkdir /var/lib/dpkg/info/
sudo apt-get update
sudo apt-get -f install
没有报错之后,再执行如下命令
sudo mv /var/lib/dpkg/info/* /var/lib/dpkg/info_old/
sudo rm -rf /var/lib/dpkg/info
sudo mv /var/lib/dpkg/info_old /var/lib/dpkg/info   
sudo apt-get update
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

(2)安装p4a
$ pip3 install python-for-android

2.1.2 安装Android SDK/NDK

注意SDK/NDK的版本,请安装推荐的版本
(1)下载SDK
在下列网页下载Android-SDK。
在这里插入图片描述文件名commandlinetools-linux-6858069_latest.zip
(2)下载NDK
下载Android-NDK,放置于C:\Users\user\Desktop文件夹,官方要求版本r19b。可以直接点击r19b下载链接: https://dl.google.com/android/repository/android-ndk-r19b-linux-x86_64.zip?hl=zh_cn

(3)安装

$ mkdir ~/androidsdk
$ cd ~/androidsdk/
$ unzip /mnt/c/Users/user/Desktop/commandlinetools-linux-6858069_latest.zip

$ mkdir ~/Android
$ cd ~/Android
$ mkdir SDK
$ unzip /mnt/c/Users/user/Desktop/android-ndk-r19b-linux-x86_64.zip
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

(4)部署cmdline-tools

$ cd ~/androidsdk/cmdline-tools/bin
$ ./sdkmanager --sdk_root=$HOME/Android/SDK "cmdline-tools;latest"  
  • 1
  • 2

(5)添加环境变量

$ vi ~/.bashrc
export ANDROID_SDK_ROOT="$HOME/Android/SDK"
export PATH=$PATH:~/.local/bin/:$ANDROID_SDK_ROOT/cmdline-tools/latest/bin/:$ANDROID_SDK_ROOT/tools/:$ANDROID_SDK_ROOT/platform-tools/
 
export ANDROIDSDK="$HOME/Android/SDK"
export ANDROIDNDK="$HOME/Android/android-ndk-r19b"
export ANDROIDAPI="27"  # Target API version of your application
export NDKAPI="21"      # Minimum supported API version of your application
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

  • 1

删除之前zip文件解压缩的sdk文件夹
$ rm -rf androidsdk/
Ctrl+D关闭窗口,然后再次打开Ubuntu

2.1.3 安装API platform和build-tools

安装 API platform,推荐的API level是27。

$ sdkmanager "platforms;android-27"
$ sdkmanager "build-tools;29.0.0"
可以列举所有可以安装的build-tools的版本
$ sdkmanager --list | grep build-tools
  • 1
  • 2
  • 3
  • 4

2.1.4 安装jdk8

$ sudo apt-get remove openjdk*  卸载自带的openjdk
$ cp /mnt/c/Users/user/Desktop/jdk-8u181-linux-x64.tar.gz /home/phone
$ tar -xzvf jdk-8u181-linux-x64.tar.gz -C /home/phone
$ sudo ln -s /home/phone/jdk1.8.0_181/bin/java /usr/bin/java
  • 1
  • 2
  • 3
  • 4

2.2 打包使用

To build your application, you need to specify name, version, a package identifier, the bootstrap you want to use (sdl2 for kivy or sdl2 apps) and the requirements:

2.2.1 创建工程

$ mkdir ~/helloworld
$ cd ~/helloworld
$ vi main.py
from kivy.app import App
from kivy.uix.button import Button

class TestApp(App):
    def build(self):
        return Button(text='Hello,kivy')
TestApp().run()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2.2.2 打包命令

$p4a apk --private $HOME/helloworld --package=org.example.myapp --name “My application” --version 0.1 --bootstrap=sdl2 --requirements=python3,kivy==2.0.0
需要注意的是–private $HOME/helloworld是为了指定项目所在的文件夹。

如果重新打包,可通过下面的命令清除所有下载和构建的内容:
p4a clean_all
如果只想清理内部版本以避免重新下载依赖项,执行下面的命令:
p4a clean_builds && p4a clean_dists

2.2.3 异常及解决

(1)ubuntu configure: error: C compiler cannot create executables

$sudo apt-get install clang && rvm install 1.9.3 --with-gcc=clang
$  sudo apt-get install build-essential
$ sudo apt-get install --reinstall build-essential
$ sudo apt-get install --reinstall gcc
$ sudo dpkg-reconfigure build-essential
$ sudo dpkg-reconfigure gcc
$ sudo apt install gobjc++
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

(2)无法安装Kivy(Windows 10,python 3.8)

$p4a apk --private $HOME/helloworld 
--package=org.example.myapp 
--name "My application" 
--version 0.1 
--bootstrap=sdl2 
--requirements=python3,kivy
未指定kivy的版本,默认下载kivy-1.11.1有问题。

$p4a apk --private $HOME/helloworld 
--package=org.example.myapp 
--name "My application" 
--version 0.1 
--bootstrap=sdl2 
--requirements=python3,kivy==2.0.0
最新的Kivy稳定版确实支持Python 3.8,它可以正常工作
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

3 使用Buildozer打包apk【成功】

将Py文件打包成apk文件,暂有如下3个方法:
(1)通过Buildozer;(在linux环境下实现,集成式框架比较容易实现)。
(2)通过python for android,(这种可以在windows下实现,但需要安装和配置许多内容,较为繁琐)。
(3)通过Kivy Launcher上打包(需要用到谷歌市场,鉴于网络,建议选择别的)。

Kivy官方提供了打包工具buildozer,该工具使用十分简便,其内部实际上是使用python-to-android完成的。但是这个工具目前只能在Linux系统上使用,因此对于windows用户,需要先安装一个虚拟机。

3.1 安装工具

3.1.1 安装ubuntu虚拟机

(1)安装virtualbox
(2)下载镜像文件ubuntu-22.04.2-live-server-amd64.iso。
(3)virtualbox创建新的虚拟机
(4)操作系统
用户名和密码ubuntu/bigdata

3.1.2 安装Buildozer及其依赖项

Buildozer官网安装配置
以Ubuntu系统为例

(1)首先安装pip:
sudo apt install python3-pip

(2)接着使用pip安装buildozer:
pip3 install buildozer

(3)然后安装buildozer的依赖项:
sudo apt update
sudo apt install -y git zip unzip openjdk-17-jdk python3-pip autoconf libtool pkg-config zlib1g-dev libncurses5-dev libncursesw5-dev libtinfo5 cmake libffi-dev libssl-dev lld
pip3 install Cython
pip3 install virtualenv

(4)然后在~/.bashrc文件中加入环境变量
sudo vim ~/.bashrc
将光标移至文件末尾,按i进入编辑(插入)模式。
另起一行,将下面代码添加在文件末尾:
export PATH=$PATH:~/.local/bin/
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

3.2 打包使用

3.2.1 使用Buildozer打包

一、进入需要打包的py文件所在文件夹,执行命令:

buildozer init
  • 1

这会在目录下生成一个名为buildozer.spec的文件,里面申明了这个程序的一些配置信息。其中第一项和第二项分别指程序名称和安装包的名称,主要修改这两项即可。

注意:第一项程序名称是在手机上安装后显示在桌面图标下方的名字,这一项中可以有空格;第二项安装包名称是生成的apk的名称,这一项的值不可以有空格和其他特殊符号,包括连字符“-”。

二、修改完成后,使用以下命令开始打包:

buildozer -v android debug
  • 1

注意:
buildozer会将目录内所有指定了后缀名(在.spec文件中指定)的文件都打包进去,并且main.py作为程序入口。第一次打包的过程速度比较慢,因为要下载Android SDK等工具,往后的打包不会像第一次这么慢。Android SDK的大小大于5G,请确保磁盘空间足够。

该命令将在同级目录bin文件夹下生成一个调试版的apk文件。首次打包过程需要安装很多依赖和包,且需要同意一个协议。打包完成后,将apk文件安装到Android手机中,安装后即可打开。

3.2.2 问题及解决

(1)Kivy Apk build with buildozer错误:
找不到Java编译器(javac),请安装
Java compiler (javac) not found, please install it.
javac -version
sudo apt install openjdk-11-jdk-headless

(2)下载不到hostpython3
I’m trying to build an app with buildozer, and it gets stuck when downloading hostpython3. The last message is: [INFO]: Downloading hostpython3 from https://www.python.org/ftp/python/3.10.10/Python-3.10.10.tgz and it never gets downloaded. I tried downloading it manually and placing it in …/Python/kivy_sms/.buildozer/android/platform/build-armeabi-v7a/packages, but it removes it and does the same thing. Is there a way to bypass this and download it manually?

操作如下:
/home/ubuntu/helloworld/.buildozer/android/platform/build-arm64-v8a_armeabi-v7a/packages/hostpython3
离线下载Python-3.10.10.tgz放置到上述目录
然后创建文件。
touch .mark-Python-3.10.10.tgz
下载不下来的文件,就离线下载,然后创建标记文件。
touch .mark-setuptools-51.3.3.tar.gz

3.2.3 压缩.buildozer

注意.buildozer保存结合buildozer.spec,方便以后打包使用。
在这里插入图片描述

3.3 buildozer.spec文件

使用cd命令进入需要打包项目的同级目录,执行以下命令:
$ buildozer init
这将在项目同级目录中生成一个buildozer.spec文件。使用该文件可以对打包的App进行配置(包括App名称、图标、版本等)。


[app]

# (str) Title of your application
# 应用名称
title = My Application

# (str) Package name
# 包名
package.name = myapp

# (str) Package domain (needed for android/ios packaging)
# 域名
package.domain = org.test

# (str) Source code where the main.py live
# main文件所在位置
source.dir = .

# (list) Source files to include (let empty to include all the files)
# 需要打包进来的文件扩展名
source.include_exts = py,png,jpg,kv,atlas

# (list) List of inclusions using pattern matching
#source.include_patterns = assets/*,images/*.png

# (list) Source files to exclude (let empty to not exclude anything)
#source.exclude_exts = spec

# (list) List of directory to exclude (let empty to not exclude anything)
#source.exclude_dirs = tests, bin, venv

# (list) List of exclusions using pattern matching
# Do not prefix with './'
#source.exclude_patterns = license,images/*/*.jpg

# (str) Application versioning (method 1)
# 应用版本
version = 0.1

# (str) Application versioning (method 2)
# version.regex = __version__ = ['"](.*)['"]
# version.filename = %(source.dir)s/main.py

# (list) Application requirements
# comma separated e.g. requirements = sqlite3,kivy
# 应用依赖包
requirements = python3,kivy

# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
# requirements.source.kivy = ../../kivy

# (str) Presplash of the application
#presplash.filename = %(source.dir)s/data/presplash.png

# (str) Icon of the application
#icon.filename = %(source.dir)s/data/icon.png

# (list) Supported orientations
# Valid options are: landscape, portrait, portrait-reverse or landscape-reverse
# 应用支持的方向
orientation = portrait

# (list) List of service to declare
#services = NAME:ENTRYPOINT_TO_PY,NAME2:ENTRYPOINT2_TO_PY

#
# OSX Specific
#

#
# author = © Copyright Info

# change the major version of python used by the app
osx.python_version = 3

# Kivy version to use
osx.kivy_version = 1.9.1

#
# Android specific
#

# (bool) Indicate if the application should be fullscreen or not
# 全屏显示1,非全屏0
fullscreen = 0

# (string) Presplash background color (for android toolchain)
# Supported formats are: #RRGGBB #AARRGGBB or one of the following names:
# red, blue, green, black, white, gray, cyan, magenta, yellow, lightgray,
# darkgray, grey, lightgrey, darkgrey, aqua, fuchsia, lime, maroon, navy,
# olive, purple, silver, teal.
#android.presplash_color = #FFFFFF

# (string) Presplash animation using Lottie format.
# see https://lottiefiles.com/ for examples and https://airbnb.design/lottie/
# for general documentation.
# Lottie files can be created using various tools, like Adobe After Effect or Synfig.
#android.presplash_lottie = "path/to/lottie/file.json"

# (str) Adaptive icon of the application (used if Android API level is 26+ at runtime)
#icon.adaptive_foreground.filename = %(source.dir)s/data/icon_fg.png
#icon.adaptive_background.filename = %(source.dir)s/data/icon_bg.png

# (list) Permissions
# (See https://python-for-android.readthedocs.io/en/latest/buildoptions/#build-options-1 for all the supported syntaxes and properties)
#android.permissions = android.permission.INTERNET, (name=android.permission.WRITE_EXTERNAL_STORAGE;maxSdkVersion=18)

# (list) features (adds uses-feature -tags to manifest)
#android.features = android.hardware.usb.host

# (int) Target Android API, should be as high as possible.
#android.api = 31

# (int) Minimum API your APK / AAB will support.
#android.minapi = 21

# (int) Android SDK version to use
#android.sdk = 20

# (str) Android NDK version to use
#android.ndk = 23b

# (int) Android NDK API to use. This is the minimum API your app will support, it should usually match android.minapi.
#android.ndk_api = 21

# (bool) Use --private data storage (True) or --dir public storage (False)
#android.private_storage = True

# (str) Android NDK directory (if empty, it will be automatically downloaded.)
#android.ndk_path =

# (str) Android SDK directory (if empty, it will be automatically downloaded.)
#android.sdk_path =

# (str) ANT directory (if empty, it will be automatically downloaded.)
#android.ant_path =

# (bool) If True, then skip trying to update the Android sdk
# This can be useful to avoid excess Internet downloads or save time
# when an update is due and you just want to test/build your package
# android.skip_update = False

# (bool) If True, then automatically accept SDK license
# agreements. This is intended for automation only. If set to False,
# the default, you will be shown the license when first running
# buildozer.
# android.accept_sdk_license = False

# (str) Android entry point, default is ok for Kivy-based app
#android.entrypoint = org.kivy.android.PythonActivity

# (str) Full name including package path of the Java class that implements Android Activity
# use that parameter together with android.entrypoint to set custom Java class instead of PythonActivity
#android.activity_class_name = org.kivy.android.PythonActivity

# (str) Extra xml to write directly inside the <manifest> element of AndroidManifest.xml
# use that parameter to provide a filename from where to load your custom XML code
#android.extra_manifest_xml = ./src/android/extra_manifest.xml

# (str) Extra xml to write directly inside the <manifest><application> tag of AndroidManifest.xml
# use that parameter to provide a filename from where to load your custom XML arguments:
#android.extra_manifest_application_arguments = ./src/android/extra_manifest_application_arguments.xml

# (str) Full name including package path of the Java class that implements Python Service
# use that parameter to set custom Java class which extends PythonService
#android.service_class_name = org.kivy.android.PythonService

# (str) Android app theme, default is ok for Kivy-based app
# android.apptheme = "@android:style/Theme.NoTitleBar"

# (list) Pattern to whitelist for the whole project
#android.whitelist =

# (str) Path to a custom whitelist file
#android.whitelist_src =

# (str) Path to a custom blacklist file
#android.blacklist_src =

# (list) List of Java .jar files to add to the libs so that pyjnius can access
# their classes. Don't add jars that you do not need, since extra jars can slow
# down the build process. Allows wildcards matching, for example:
# OUYA-ODK/libs/*.jar
#android.add_jars = foo.jar,bar.jar,path/to/more/*.jar

# (list) List of Java files to add to the android project (can be java or a
# directory containing the files)
#android.add_src =

# (list) Android AAR archives to add
#android.add_aars =

# (list) Put these files or directories in the apk assets directory.
# Either form may be used, and assets need not be in 'source.include_exts'.
# 1) android.add_assets = source_asset_relative_path
# 2) android.add_assets = source_asset_path:destination_asset_relative_path
#android.add_assets =

# (list) Put these files or directories in the apk res directory.
# The option may be used in three ways, the value may contain one or zero ':'
# Some examples:
# 1) A file to add to resources, legal resource names contain ['a-z','0-9','_']
# android.add_resources = my_icons/all-inclusive.png:drawable/all_inclusive.png
# 2) A directory, here  'legal_icons' must contain resources of one kind
# android.add_resources = legal_icons:drawable
# 3) A directory, here 'legal_resources' must contain one or more directories,
# each of a resource kind:  drawable, xml, etc...
# android.add_resources = legal_resources
#android.add_resources =

# (list) Gradle dependencies to add
#android.gradle_dependencies =

# (bool) Enable AndroidX support. Enable when 'android.gradle_dependencies'
# contains an 'androidx' package, or any package from Kotlin source.
# android.enable_androidx requires android.api >= 28
#android.enable_androidx = True

# (list) add java compile options
# this can for example be necessary when importing certain java libraries using the 'android.gradle_dependencies' option
# see https://developer.android.com/studio/write/java8-support for further information
# android.add_compile_options = "sourceCompatibility = 1.8", "targetCompatibility = 1.8"

# (list) Gradle repositories to add {can be necessary for some android.gradle_dependencies}
# please enclose in double quotes
# e.g. android.gradle_repositories = "maven { url 'https://kotlin.bintray.com/ktor' }"
#android.add_gradle_repositories =

# (list) packaging options to add
# see https://google.github.io/android-gradle-dsl/current/com.android.build.gradle.internal.dsl.PackagingOptions.html
# can be necessary to solve conflicts in gradle_dependencies
# please enclose in double quotes
# e.g. android.add_packaging_options = "exclude 'META-INF/common.kotlin_module'", "exclude 'META-INF/*.kotlin_module'"
#android.add_packaging_options =

# (list) Java classes to add as activities to the manifest.
#android.add_activities = com.example.ExampleActivity

# (str) OUYA Console category. Should be one of GAME or APP
# If you leave this blank, OUYA support will not be enabled
#android.ouya.category = GAME

# (str) Filename of OUYA Console icon. It must be a 732x412 png image.
#android.ouya.icon.filename = %(source.dir)s/data/ouya_icon.png

# (str) XML file to include as an intent filters in <activity> tag
#android.manifest.intent_filters =

# (list) Copy these files to src/main/res/xml/ (used for example with intent-filters)
#android.res_xml = PATH_TO_FILE,

# (str) launchMode to set for the main activity
#android.manifest.launch_mode = standard

# (str) screenOrientation to set for the main activity.
# Valid values can be found at https://developer.android.com/guide/topics/manifest/activity-element
#android.manifest.orientation = fullSensor

# (list) Android additional libraries to copy into libs/armeabi
#android.add_libs_armeabi = libs/android/*.so
#android.add_libs_armeabi_v7a = libs/android-v7/*.so
#android.add_libs_arm64_v8a = libs/android-v8/*.so
#android.add_libs_x86 = libs/android-x86/*.so
#android.add_libs_mips = libs/android-mips/*.so

# (bool) Indicate whether the screen should stay on
# Don't forget to add the WAKE_LOCK permission if you set this to True
#android.wakelock = False

# (list) Android application meta-data to set (key=value format)
#android.meta_data =

# (list) Android library project to add (will be added in the
# project.properties automatically.)
#android.library_references =

# (list) Android shared libraries which will be added to AndroidManifest.xml using <uses-library> tag
#android.uses_library =

# (str) Android logcat filters to use
#android.logcat_filters = *:S python:D

# (bool) Android logcat only display log for activity's pid
#android.logcat_pid_only = False

# (str) Android additional adb arguments
#android.adb_args = -H host.docker.internal

# (bool) Copy library instead of making a libpymodules.so
#android.copy_libs = 1

# (list) The Android archs to build for, choices: armeabi-v7a, arm64-v8a, x86, x86_64
# In past, was `android.arch` as we weren't supporting builds for multiple archs at the same time.
android.archs = armeabi-v7a

# (int) overrides automatic versionCode computation (used in build.gradle)
# this is not the same as app version and should only be edited if you know what you're doing
# android.numeric_version = 1

# (bool) enables Android auto backup feature (Android API >=23)
android.allow_backup = True

# (str) XML file for custom backup rules (see official auto backup documentation)
# android.backup_rules =

# (str) If you need to insert variables into your AndroidManifest.xml file,
# you can do so with the manifestPlaceholders property.
# This property takes a map of key-value pairs. (via a string)
# Usage example : android.manifest_placeholders = [myCustomUrl:\"org.kivy.customurl\"]
# android.manifest_placeholders = [:]

# (bool) Skip byte compile for .py files
# android.no-byte-compile-python = False

# (str) The format used to package the app for release mode (aab or apk or aar).
# android.release_artifact = aab

# (str) The format used to package the app for debug mode (apk or aar).
# android.debug_artifact = apk

#
# Python for android (p4a) specific
#

# (str) python-for-android URL to use for checkout
#p4a.url =

# (str) python-for-android fork to use in case if p4a.url is not specified, defaults to upstream (kivy)
#p4a.fork = kivy

# (str) python-for-android branch to use, defaults to master
#p4a.branch = master

# (str) python-for-android specific commit to use, defaults to HEAD, must be within p4a.branch
#p4a.commit = HEAD

# (str) python-for-android git clone directory (if empty, it will be automatically cloned from github)
#p4a.source_dir =

# (str) The directory in which python-for-android should look for your own build recipes (if any)
#p4a.local_recipes =

# (str) Filename to the hook for p4a
#p4a.hook =

# (str) Bootstrap to use for android builds
# p4a.bootstrap = sdl2

# (int) port number to specify an explicit --port= p4a argument (eg for bootstrap flask)
#p4a.port =

# Control passing the --use-setup-py vs --ignore-setup-py to p4a
# "in the future" --use-setup-py is going to be the default behaviour in p4a, right now it is not
# Setting this to false will pass --ignore-setup-py, true will pass --use-setup-py
# NOTE: this is general setuptools integration, having pyproject.toml is enough, no need to generate
# setup.py if you're using Poetry, but you need to add "toml" to source.include_exts.
#p4a.setup_py = false

# (str) extra command line arguments to pass when invoking pythonforandroid.toolchain
#p4a.extra_args =



#
# iOS specific
#

# (str) Path to a custom kivy-ios folder
#ios.kivy_ios_dir = ../kivy-ios
# Alternately, specify the URL and branch of a git checkout:
ios.kivy_ios_url = https://github.com/kivy/kivy-ios
ios.kivy_ios_branch = master

# Another platform dependency: ios-deploy
# Uncomment to use a custom checkout
#ios.ios_deploy_dir = ../ios_deploy
# Or specify URL and branch
ios.ios_deploy_url = https://github.com/phonegap/ios-deploy
ios.ios_deploy_branch = 1.10.0

# (bool) Whether or not to sign the code
ios.codesign.allowed = false

# (str) Name of the certificate to use for signing the debug version
# Get a list of available identities: buildozer ios list_identities
#ios.codesign.debug = "iPhone Developer: <lastname> <firstname> (<hexstring>)"

# (str) The development team to use for signing the debug version
#ios.codesign.development_team.debug = <hexstring>

# (str) Name of the certificate to use for signing the release version
#ios.codesign.release = %(ios.codesign.debug)s

# (str) The development team to use for signing the release version
#ios.codesign.development_team.release = <hexstring>

# (str) URL pointing to .ipa file to be installed
# This option should be defined along with `display_image_url` and `full_size_image_url` options.
#ios.manifest.app_url =

# (str) URL pointing to an icon (57x57px) to be displayed during download
# This option should be defined along with `app_url` and `full_size_image_url` options.
#ios.manifest.display_image_url =

# (str) URL pointing to a large icon (512x512px) to be used by iTunes
# This option should be defined along with `app_url` and `display_image_url` options.
#ios.manifest.full_size_image_url =


[buildozer]

# (int) Log level (0 = error only, 1 = info, 2 = debug (with command output))
log_level = 2

# (int) Display warning if buildozer is run as root (0 = False, 1 = True)
warn_on_root = 1

# (str) Path to build artifact storage, absolute or relative to spec file
# build_dir = ./.buildozer

# (str) Path to build output (i.e. .apk, .aab, .ipa) storage
# bin_dir = ./bin

#    -----------------------------------------------------------------------------
#    List as sections
#
#    You can define all the "list" as [section:key].
#    Each line will be considered as a option to the list.
#    Let's take [app] / source.exclude_patterns.
#    Instead of doing:
#
#[app]
#source.exclude_patterns = license,data/audio/*.wav,data/images/original/*
#
#    This can be translated into:
#
#[app:source.exclude_patterns]
#license
#data/audio/*.wav
#data/images/original/*
#


#    -----------------------------------------------------------------------------
#    Profiles
#
#    You can extend section / key with a profile
#    For example, you want to deploy a demo version of your application without
#    HD content. You could first change the title to add "(demo)" in the name
#    and extend the excluded directories to remove the HD content.
#
#[app@demo]
#title = My Application (demo)
#
#[app:source.exclude_patterns@demo]
#images/hd/*
#
#    Then, invoke the command line with the "demo" profile:
#
#buildozer --profile demo android debug

  • 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
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336
  • 337
  • 338
  • 339
  • 340
  • 341
  • 342
  • 343
  • 344
  • 345
  • 346
  • 347
  • 348
  • 349
  • 350
  • 351
  • 352
  • 353
  • 354
  • 355
  • 356
  • 357
  • 358
  • 359
  • 360
  • 361
  • 362
  • 363
  • 364
  • 365
  • 366
  • 367
  • 368
  • 369
  • 370
  • 371
  • 372
  • 373
  • 374
  • 375
  • 376
  • 377
  • 378
  • 379
  • 380
  • 381
  • 382
  • 383
  • 384
  • 385
  • 386
  • 387
  • 388
  • 389
  • 390
  • 391
  • 392
  • 393
  • 394
  • 395
  • 396
  • 397
  • 398
  • 399
  • 400
  • 401
  • 402
  • 403
  • 404
  • 405
  • 406
  • 407
  • 408
  • 409
  • 410
  • 411
  • 412
  • 413
  • 414
  • 415
  • 416
  • 417
  • 418
  • 419
  • 420
  • 421
  • 422
  • 423
  • 424
  • 425
  • 426
  • 427
  • 428
  • 429
  • 430
  • 431
  • 432
  • 433
  • 434
  • 435
  • 436
  • 437
  • 438
  • 439
  • 440
  • 441
  • 442
  • 443
  • 444
  • 445
  • 446
  • 447
  • 448
  • 449
  • 450
  • 451
  • 452
  • 453
  • 454
  • 455
  • 456
  • 457
  • 458
  • 459
  • 460
  • 461
  • 462
  • 463

3.4 解释

主要后构建的Android框架,可选项: armeabi-v7a, arm64-v8a, x86, x86_64
android.arch = armeabi-v7a

4 使用kivydev64 v5.0虚拟机打包apk

kivydev64 v5.0的GitHub地址
镜像下载地址天翼网盘下载速度超级快 (访问码:1ha9)
VirtualBox扩展工具下载地址
p4a官方文档

4.1 安装虚拟机

一、下载虚拟机镜像kivydev64 v5.0

kivy打包apk推荐使用打包环境虚拟机kivydev64 v5.0。
Vbox+Ubuntu16.04打包生成kivy apk
特点如下:
采用buildozer
编译安装了python37
kivy升级到最新稳定版
ndk升级到r19c
jnius、matplotlib、numpy打包测试通过
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

下载好的镜像文件大概18G,双击第一个文件会自动解压所有文件为kivydev64-5.0.ova。ova文件扩展是Open Virtual Appliance为Oracle VM VirtualBox软件程序开发的Oracle Corporation文件类型。
在这里插入图片描述
(1)打开virtualbox软件
管理->导入虚拟电脑,选择解压出的ova格式文件。
选择打开的虚拟机的初始位置D:\LINUXOS\kivypackage。
打开需要耗时大约20min。
(2)设置share目录,为了导入和导出python文件,apk等文件。
设置->共享文件夹->共享文件夹路径D:\share,共享名称share。
在这里插入图片描述
启动系统会后会看到自动挂载的目录/media/sf_share/。

二、系统Ubuntu 16.04,装了xfce桌面。
打包环境已经包含了增强工具,支持共享文件夹,调整分辨率。
用户名 kivydev 密码 kivydev 用户名 root 密码 root。
视图->自动调整窗口大小
视图->自动调整显示尺寸

4.2 打包应用

必须使用main.py命名才能进行打包,先在目录下对main.py进行编译,看能否成功执行:
python3 main.py

cd /home/kivydev/test
mkdir myuse
cd myuse
编写main.py放到myuse目录中
将buildozer.spec复制到myuse目录中以供使用。

buildozer android debug
如果有问题,执行清理
buildozer android clean
后再执行上述的打包部署
buildozer android debug

打包完成以后可以在bin目录下看到apk文件。
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

5 应用示例

Kivy总体思想是:kv代码管界面,python代码管逻辑。

在Python中的代码中经常会见到这两个词 args 和 kwargs,前面通常还会加上一个或者两个星号。其实这只是编程人员约定的变量名字,args 是 arguments 的缩写,表示位置参数;kwargs 是 keyword arguments 的缩写,表示关键字参数。这其实就是 Python 中可变参数的两种形式,并且 *args 必须放在 **kwargs 的前面,因为位置参数在关键字参数的前面。

5.1 hello world

5.1.1 纯python文件

文件main.py

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

class IndexPage(BoxLayout):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        self.btn = Button(text = "helloworld")
        self.add_widget(self.btn)

class TestApp(App):
    def build(self):
        return IndexPage()

if __name__ == "__main__":
    TestApp().run()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

5.1.2 python文件和.kv文件

将下面的两行代码替换掉
self.btn = Button(text = “helloworld”)
self.add_widget(self.btn)

文件test.kv

<IndexPage>:
    Button:
        text: "helloworld"
  • 1
  • 2
  • 3

文件main.py

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

class IndexPage(BoxLayout):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)

class TestApp(App):
    def build(self):
        return IndexPage()

if __name__ == "__main__":
    TestApp().run()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

5.2 button按钮事件

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

class IndexPage(BoxLayout):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        self.btn = Button(text = "press me")
        self.btn.bind(on_press = self.press_button)
        self.add_widget(self.btn)

    def press_button(self, arg):
        print("press button is running")
        
class TestApp(App):
    def build(self):
        return IndexPage()

if __name__ == "__main__":
    TestApp().run()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

5.3 Label标签

下载字体支持中文

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

class IndexPage(BoxLayout):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        # Button按钮
        self.btn = Button(text = "press me")
        self.btn.bind(on_press = self.press_button)
        self.add_widget(self.btn)
        # Label标签
        self.la = Label(font_name = "./arialuni.ttf")
        self.add_widget(self.la)
    def press_button(self, arg):
        self.la.text = "show you看"

class TestApp(App):
    def build(self):
        return IndexPage()

if __name__ == "__main__":
    TestApp().run()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/471515
推荐阅读
相关标签
  

闽ICP备14008679号