0

我是 android 上的 python 新手,我正在尝试构建一个在这里找到的 web 应用程序的小示例(http://pythoncentral.io/python-for-android-using-webviews-sl4a/),其中 python 脚本打开一个网页并与之通信(您在网页中输入文本,python脚本对其进行处理并将其发送回网页以进行显示)。在我尝试执行此操作时,python 脚本可以打开页面,但网页和脚本之间没有对话。网页中的“var android = new Android()”行似乎不像示例中那样工作。

这是网页的代码:

<!DOCTYPE HTML>
<html>
    <head>
        <script>
            var droid = new Android();

            function postInput(input) {
                if (event.keyCode == 13)
                    droid.eventPost('line', input)

                droid.registerCallback('stdout', function(e) {
                    document.getElementById('output').innerHTML = e.data;
                });
            }
        </script>   
    </head> 
    <body>
        <div id="banner">
            <h1>SL4A Webviews</h1>
            <h2>Example: Python Evaluator</h2>
        </div>

        <input id="userin" type="text" spellcheck="false"
               autofocus="autofocus" onkeyup="postInput(this.value)"
        />

        <div id="output"></div>

        <button id="killer" type="button"
                onclick="droid.eventPost('kill', '')"
        >QUIT</button>
    </body>
</html>

以及启动上面网页的python代码:

import sys, androidhelper
droid = androidhelper.Android()

def line_handler(line):
    ''' Evaluate user input and print the result into a webview.
    This function takes a line of user input and calls eval on
    it, posting the result to the webview as a stdout event.
    '''
    output = str(eval(line))
    droid.eventPost('stdout', output)

droid.webViewShow('file:///storage/emulated/0/com.hipipal.qpyplus/scripts/webview1.html')

while True:
    event = droid.eventWait().result

    if event['name'] == 'kill':
        sys.exit()
    elif event['name'] == 'line':
        line_handler(event['data'])

我真的不明白网页中的 Android() 实例应该如何工作。感谢您的任何帮助 !(我在 android lollipop 上使用 SL4A 库运行 qpython)

4

1 回答 1

0

昨天终于发现qpython自带了一个不错的框架,叫做Bottle。对于像我这样的初学者来说,它非常容易使用。

from bottle import route, run, request, template

@route('/hello')
def hello():
    line = ""
    output = ""
    return template('/storage/emulated/0/com.hipipal.qpyplus/webviewbottle2.tpl', line=line, output=output)

@route('/submit', method='POST')
def submit():
    line = request.forms.get('line')
    output = str(eval(line))
    return template('/storage/emulated/0/com.hipipal.qpyplus/webviewbottle2.tpl', line=line, output=output)

run(host='localhost', port=8080, debug=True)    

# open a web browser with http://127.0.0.1:8080/hello to start
# enter 40 + 2 in the input and "submit" to get the answer in the output window.

和模板文件:

<h1>bottle Webview</h1>
<h2>Example: Python Evaluator</h2>
<form action="/submit" method = "post">
    <input name="line" type = "text" value = {{line}}><br>
    <input name="output" type = "text" value = {{output}}>
    <button name="submit" type = "submit">submit</button>
</form>
于 2016-06-10T11:06:22.277 回答