1

I'm trying to use an example provided by the Flet developers written in Python Flet framework. After having installed Flet, and downloaded the example, I tried to run it into Spyder IDE 5.5. When I ran it, I got this error:

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

How can I solve it? Thank you in advance.

2
  • 1
    I think the issue arises because asyncio.run() is called directly inside the ft.app() function, which is causing the error because it's already running within an event loop. You can run the Flet app inside a separate event loop. Commented Apr 7, 2024 at 10:37
  • Could you please specify how to run the Flet app inside a separate event loop? Commented Apr 7, 2024 at 10:53

1 Answer 1

2

When trying to use asynchronous code in environments that already have an event loop running you encounter the error: RuntimeError: asyncio.run() cannot be called from a running event loop

Your best bet is to modify the script:

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))

If it doesn't work you should try running your script outside the IDE.

Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately, running your code gave me the same error. I solved it running the code from CLI. Thank you anyway.
Same, runs from CL but not from within Spyder

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.