Is it possible to run only a single step of the asyncio event loop

前端 未结 3 1339
北恋
北恋 2020-12-10 05:31

I\'m working on a simple graphical network application, using asyncio and tkinter. I\'m running into the problem of combining the asyncio event loop with Tk\'s mainloop. If

3条回答
  •  温柔的废话
    2020-12-10 05:57

    Take a look at this example.

    import asyncio
    from tkinter import *
    
    class asyncTk(Tk):
        def __init__(self):
            super().__init__()
            self.running = True
            self.protocol("WM_DELETE_WINDOW", self.on_closing)
    
        def on_closing(self):
            self.running = False
            self.destroy()
            
        def __await__(self):
            while self.running:
                self.update()
                yield
    
    async def asd():
        for x in range(1,10):
            await asyncio.sleep(1)
            print(x)
    
    async def main():
        w = asyncTk()
        asyncio.create_task(asd())
        await w
    
    asyncio.run(main())
    

提交回复
热议问题