我是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()实例应该如何工作。感谢您的任何帮助!(我在安卓棒棒糖上运行带有SL4A库的qpython)
昨天我发现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>