我是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棒棒糖上使用SL4A库运行qpython)
答案 0 :(得分:0)
最后昨天我发现qpython附带了一个名为Bottle的漂亮框架。对于像我这样的初学者来说它非常容易使用。
ON DELETE
和模板文件:
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.