PyScript中input使用问题:Chrome中常规Python输入失效的简易替代方案
解决PyScript中input()阻塞页面且无提示的问题
问题原因
PyScript运行在浏览器主线程中,原生Python的input()是阻塞式调用,会直接卡住页面加载直到输入完成,且不会在页面上显示输入提示文本。
解决方案
使用PyScript提供的异步输入方法,无需编写JavaScript,写法和常规input()接近,具体实现如下:
修改后的代码
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> <script defer src="https://pyscript.net/latest/pyscript.js"></script> <body> <py-script> import pyscript async def main(): print("welcome to madlibs!") print('please do not put any spaces in your answers') print("\n\n") name1 = await pyscript.input('name?') print(f"Hello, {name1}!") main() </py-script> </body>
关键说明
- 异步函数
main()配合await pyscript.input(),不会阻塞浏览器主线程,页面能正常加载完成后再弹出带提示的输入框 - 输入框会显示指定的提示文本(示例中为
name?),行为和常规Python的input()一致 - 输入完成后,后续代码会正常执行,比如示例中打印输入的名字
内容的提问来源于stack exchange,提问作者K K
相关产品推荐
相关产品推荐

