栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

一起使用asyncio和Tkinter(或另一个GUI库),而无需冻结GUI

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

一起使用asyncio和Tkinter(或另一个GUI库),而无需冻结GUI

在对您的代码进行稍作修改后,我

event_loop
在主线程中创建了asyncio并将其作为参数传递给asyncio线程。现在,在提取网址时,Tkinter不会冻结。

from tkinter import *from tkinter import messageboximport asyncioimport threadingimport randomdef _asyncio_thread(async_loop):    async_loop.run_until_complete(do_urls())def do_tasks(async_loop):    """ Button-Event-Handler starting the asyncio part. """    threading.Thread(target=_asyncio_thread, args=(async_loop,)).start()async def one_url(url):    """ One task. """    sec = random.randint(1, 8)    await asyncio.sleep(sec)    return 'url: {}tsec: {}'.format(url, sec)async def do_urls():    """ Creating and starting 10 tasks. """    tasks = [one_url(url) for url in range(10)]    completed, pending = await asyncio.wait(tasks)    results = [task.result() for task in completed]    print('n'.join(results))def do_freezed():    messagebox.showinfo(message='Tkinter is reacting.')def main(async_loop):    root = Tk()    Button(master=root, text='Asyncio Tasks', command= lambda:do_tasks(async_loop)).pack()    buttonX = Button(master=root, text='Freezed???', command=do_freezed).pack()    root.mainloop()if __name__ == '__main__':    async_loop = asyncio.get_event_loop()    main(async_loop)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/611227.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号