用 Python 脚本实现 Android 图形用户界面

57 阅读2分钟

用户希望在 Android 设备上运行 Python 程序,并需要在其中用到列表框和简单的对话框(显示信息并获取输入)。目前,似乎只有简单的对话框,还没有找到列表框。如果缺少列表框,那么用户需要能够在屏幕上指定部分区域写入文本、高亮矩形,并响应用户的触摸或键入(包括知道用户触摸或光标所在的位置)。

2、解决方案

方法一:使用 SL4A 内置的 GUI 功能

如果您只需要简单的 Android 列表和输入,例如获取用户的输入(例如,用户名和密码)或显示可供选择的选项列表,那么可以在此处找到一些教程:code.google.com/p/android-s…

方法二:使用 WebView 显示 HTML

如果您想显示信息(即不供用户选择),则可以尝试在 WebView 中显示 HTML 并通过事件进行响应:code.google.com/p/android-s…

方法三:使用完整的 Android 布局

如果您敢于尝试,最新的非官方版本支持完整的 Android 布局(在 XML 中创建的布局,例如在原生 Android 应用中找到的布局)。您可以在此处找到相关指南:code.google.com/p/android-s…

方法四:使用 Kivy

如果您想要一个适用于 Android/iOS/Linux/Windows/Mac 的 Python GUI 解决方案,那么可以使用 Kivy。它非常好用!官方网站:kivy.org

方法五:使用 REBOL 3

REBOL 3 是一个快速而强大的选择。您可以使用 SL4A 功能,但不是必需的:business-programming.com/business_pr…

代码例子

以下是使用 REBOL 3 实现一些常用 GUI 组件的代码示例:

; Note Editor
do %r3-gui.r3
view [
    a1: area
    button "Save" on-action [write %notes.txt get-face a1]
    button "Load" on-action [set-face a1 to-string read %notes.txt]
]
; Calculator
do %r3-gui.r3
stylize [
    btn: button [
        facets: [init-size: 50x50]
        actors: [on-action:[set-face f join get-face f get-face face]]
    ]
]
view [
    hgroup [
        f: field return
        btn "1"  btn "2"  btn "3"  btn " + "  return
        btn "4"  btn "5"  btn "6"  btn " - "  return
        btn "7"  btn "8"  btn "9"  btn " * "  return
        btn "0"  btn "."  btn " / "   btn "=" on-action [
            attempt [set-face f form do get-face f]
        ]
    ]
]
; Cash Register
do %r3-gui.r3
stylize [fld: field [init-size: 80]]   
view [
    hgroup [
        text "Cashier:"   cashier: fld 
        text "Item:"      item: fld 
        text "Price:"     price: fld on-action [
            if error? try [to-money get-face price] [
                request "Error" "Price error" 
                return none
            ]
            set-face a rejoin [
                get-face a mold get-face item tab get-face price newline
            ]
            set-face item copy "" set-face price copy ""
            sum: 0
            foreach [item price] load get-face a [
                sum: sum + to-money price
            ]
            set-face subtotal form sum
            set-face tax form sum * .06
            set-face total form sum * 1.06 
            focus item
        ]
        return
        a: area 600x300
        return
        text "Subtotal:"   subtotal: fld 
        text "Tax:"        tax: fld 
        text "Total:"      total: fld
        button "Save" on-action [
            items: replace/all (mold load get-face a) newline " "
            write/append %sales.txt rejoin [
                items newline get-face cashier newline now/date newline
            ]
            set-face item copy "" set-face price copy "" 
            set-face a copy ""    set-face subtotal copy ""
            set-face tax copy "" set-face total copy ""
        ]
    ]
]