回答
在子线程中直接使用 ui
模块会报错,正确的做法是通过 ui.post
或 ui.run
切换到 UI 线程操作界面。以下是解决方案:
// 文档地址:https://docs.hamibot.com/
// 在子线程中执行耗时操作
threads.start(function() {
// 执行耗时任务...
// 通过 post 方法切换到 UI 线程
ui.post(function() {
// 在 UI 线程中创建界面
ui.layout(
<vertical>
<text text="这是表单窗口"/>
<button id="confirm" text="确定"/>
</vertical>
);
ui.confirm.on("click", function(){
toast("点击了确定");
});
});
});
// 保持脚本运行
setInterval(() => {}, 1000);
// hamibot.exit(); // 正式使用时去掉这行注释
关键点:
ui.post()
将界面操作抛到 UI 线程的消息队列- 如果希望阻塞等待 UI 操作完成,可用
ui.run()
- 不要在线程中直接操作 UI 组件
- 需要保持脚本运行(最后加
setInterval
或hamibot.wait()
)
ℹ️ 本回答由 AI 生成,内容仅供参考