需求是用 tkinter 制作的 gui 工具,点击 [开始] 后在异步函数里 while 循环,点击 [停止] 后让 while 停止
目前的问题是 asyncio.create_task 遇到 asyncio.sleep 就中断了
实际的项目中用 threading.Thread()解决了,但是不甘心还是想试试用异步解决,但还没找到解决的方法
就目前的体验来说,python 异步用起来的体验没有 node.js 来的舒服,限制挺多的
import asyncio
import time
import tkinter
from tkinter import ttk
class Window:
def __init__(self):
self.__do_while = False
root = tkinter.Tk()
root.minsize(200, 200)
frame = ttk.Frame()
frame.pack(fill=tkinter.BOTH)
ttk.Button(frame, text='开始', command=self.start).pack()
ttk.Button(frame, text='停止', command=self.stop).pack(pady=10)
root.mainloop()
def start(self):
print(time.time())
self.__do_while = True
async def go():
# 只 print 了一次就结束了
asyncio.create_task(self.exec())
# 界面卡住了
# await asyncio.create_task(self.exec())
# 界面卡住了
# await self.exec()
asyncio.run(go())
print(time.time())
def stop(self):
self.__do_while = False
async def exec(self):
i = 0
while self.__do_while:
print('exec', i)
i += 1
await asyncio.sleep(2)
if __name__ == "__main__":
Window()