在tkinter.button中传递异步函数

时间:2019-05-30 06:46:30

标签: python tkinter aiohttp

我正在制作一个应用程序,以从api请求一些数据,并希望集成GUI。 如果需要,我可以提供wilib2的代码

from tkinter import *
import asyncio
import aiohttp
import wilib2
entries = []
class WarframeEntry():
    def __init__(self, entry_name):
        self.name = entry_name

window = Tk()
window.title("Test App")
window.geometry('600x450')
lbl = Label(window, text="Enter Item Id:")
lbl.grid(column=0, row=0)
textBox = Entry(window, width=20)
textBox.grid(column=1, row=0)
async def updateDisplay():
    async with aiohttp.ClientSession() as session:
        htmls = await wilib2.fetch_all(session, entries)
        for item in htmls:
            text = Label(window, text=item['item_name'])
async def addNewEntry():
    entries.add(textBox.get())
    await updateDisplay()
btn = Button(window, text="Search", command=lambda: await asyncio.ensure_future(addNewEntry))
btn.grid(column=3, row=0)
window.mainloop()

1 个答案:

答案 0 :(得分:0)

您可以使用asyncio.new_event_loop

 def handler():
     loop = asyncio.new_event_loop()
     ss = loop.run_until_complete( async_function )
     loop.close()

有关更多详细信息,请参见calling async functions in sequential code