Python/Flet:运行时错误:无法从正在运行的事件循环调用 asyncio.run()

问题描述 投票:0回答:1

我正在尝试使用由 Flet 开发人员用 Python Flet 框架编写的 example 提供的。 安装 Flet 并下载示例后,我尝试在 Spyder IDE 5.5 中运行它。当我运行它时,我收到此错误:

运行时错误:无法从正在运行的事件循环调用 asyncio.run()

如何解决?预先感谢您。

python runtime-error python-asyncio
1个回答
0
投票

当尝试在已经运行事件循环的环境中使用异步代码时,您会遇到错误:

RuntimeError: asyncio.run() cannot be called from a running event loop

你最好的选择是修改脚本:

import asyncio
import flet as ft
async def main(page: ft.Page):
    page.title = "Flet counter example"
    page.vertical_alignment = ft.MainAxisAlignment.CENTER
    txt_number = ft.TextField(value="0", text_align=ft.TextAlign.RIGHT, width=100)
    def minus_click(e):
        txt_number.value = str(int(txt_number.value) - 1)
        page.update()
    def plus_click(e):
        txt_number.value = str(int(txt_number.value) + 1)
        page.update()
    page.add(
        ft.Row(
            [
                ft.IconButton(ft.icons.REMOVE, on_click=minus_click),
                txt_number, 
                ft.IconButton(ft.icons.ADD, on_click=plus_click),
            ],
            alignment=ft.MainAxisAlignment.CENTER,
        )
    )
if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    if loop.is_running():
        print("Can't run Flet because there's already a running event loop 😢")
    else:
        loop.run_until_complete(ft.app(target=main))

如果不起作用,您应该尝试在 IDE 之外运行脚本。

© www.soinside.com 2019 - 2024. All rights reserved.