我正在学习 py-script,您可以在 HTML5 文件中使用
<py-script></py-script>
来编写 Python 代码。作为一名Python编码员,我想在使用Python的同时尝试Web开发,因此如果我们可以使用py-script输出和输入信息将会很有帮助。
例如,有人可以解释如何让这个功能发挥作用吗:
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<div>Type an sample input here</div>
<input id = “test_input”></input>
<-- How would you get this button to display the text you typed into the input into the div with the id, “test”--!>
<button id = “submit-button” onClick = “py-script-function”>
<div id = “test”></div>
<div
<py-script>
<py-script>
</body>
</html
我将不胜感激,我希望这也能帮助其他 py-script 用户。
我在 GitHub 上检查了源代码并找到了文件夹examples。
使用文件 todo.html 和 todo.py 我创建了这个
index.html
python -m http.server
)
我发现了一些元素,因为我有一些 JavaScript 和 CSS 经验 - 所以学习 JavaScript 和 CSS 来处理 HTML 元素可能会很好。
<!DOCTYPE html>
<html>
<head>
<!--<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />-->
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<div>Type an sample input here</div>
<input type="text" id="test-input"/>
<button id="submit-button" type="submit" pys-onClick="my_function">OK</button>
<div id="test-output"></div>
<py-script>
from js import console
def my_function(*args, **kwargs):
#print('args:', args)
#print('kwargs:', kwargs)
console.log(f'args: {args}')
console.log(f'kwargs: {kwargs}')
text = Element('test-input').element.value
#print('text:', text)
console.log(f'text: {text}')
Element('test-output').element.innerText = text
</py-script>
</body>
</html>
这里是 Firefox 中
DevTool
中带有 JavaScript 控制台的屏幕截图。
加载所有模块需要更长的时间
(从
Create pyodine runtime
到Collecting nodes...
)
接下来您可以看到
console.log()
的输出。print()
,但它显示的文本带有额外错误 writing to undefined ...
。
显示输出的另一种方法是替换
Element('test-output').element.innerText = text
由
pyscript.write('test-output', text)