python中3个while循环_Python3 里怎么让一个包含 while 循环的异步函数不断运行,而不阻塞正常的代码流程...

需求是用 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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值