import tkinter as tk
import asyncio as ay
def runtask(L):
U=[]
for i in L:
U.append(ay.ensure_future(i))
ay.get_event_loop().run_until_complete(ay.wait(U))
async def f1(n):
for i in range(5):
await ay.sleep(1)
print(f'任务{n}: {5-i}')
app=tk.Tk()
app.title('动态增加异步任务')
app.geometry('500x500')
N=0
def add():
global N
N+=1
ay.gather(ay.ensure_future(f1(N)))
bt=tk.Button(app,text='增加任务',command=add)
bt.pack()
ALIVE=True
def close():
global ALIVE
ALIVE=False
app.protocol('WM_DELETE_WINDOW',close)
async def main():
while ALIVE:
app.update()
await ay.sleep(0)
ay.get_event_loop().run_until_complete(ay.ensure_future(main()))