如何将异步方法绑定到 Tkinter 中的击键?

How to bind async method to a keystroke in Tkinter?

考虑以下示例:

import asyncio
import tkinter as tk

class App(tk.Tk):

    def __init__(self):
        super().__init__()
        self.create_widgets()
        self._configure_bindings() # I believe it is not possible 
                                   # to do this if the method needs 
                                   # to be async as well

    def create_widgets(self):
        pass

    def _configure_bindings(self):
        self.bind('<F5>', self.spam) # what's the proper way?
                                     # does this method need to be async as well?

    async def spam(self, event):
        await self.do_something()

    async def do_something():
        pass

async def run_tk(root):
    try:
        while True:
            root.update()
            await asyncio.sleep(.01)
    except tk.TclError as e:
        if "application has been destroyed" not in e.args[0]:
            raise

if __name__ == '__main__':
    app = App()
    asyncio.get_event_loop().run_until_complete(run_tk(app))

在 tkinter 中将异步方法绑定到击键的正确方法是什么? 我试过类似的东西:

 self.bind('<F5>', self.spam)
 self.bind('<F5>', await self.spam)
 self.bind('<F5>', await self.spam())
 self.bind('<F5>', lambda event: await self.spam(event))

...以及其他一些组合,但无济于事。

tkinter 由于事件循环,after method and the bindings.

本身是异步的

但是,如果您尝试坚持使用 asyncio,这也是可能的,但首先让我们考虑一下您的尝试。

您的第一次尝试显然失败了,因为您试图将 spam 作为通用函数调用,而它是 coroutine。您的其他尝试比第一次更正确,但是 await coroutineyield from coroutine 只能用于从另一个协程启动协程,因此它再次失败。

所以启动那个野兽的正确方法是使用不言自明的方法ensure_future (or old async安排它的执行,这只是一个已弃用的别名)。

试试这个例子:

import asyncio
import tkinter as tk


class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self._configure_bindings()

    def _configure_bindings(self):
        self.bind('<F5>', lambda event: asyncio.ensure_future(self.spam(event)))

    async def spam(self, event):
        await self.do_something()
        await asyncio.sleep(2)
        print('%s executed!' % self.spam.__name__)

    async def do_something(self):
        print('%s executed!' % self.do_something.__name__)

async def run_tk(root):
    try:
        while True:
            root.update()
            await asyncio.sleep(.01)
    except tk.TclError as e:
        if "application has been destroyed" not in e.args[0]:
            raise

if __name__ == '__main__':
    app = App()
    asyncio.get_event_loop().run_until_complete(run_tk(app))

此外,我认为值得一提的是 问题,因为您使用的是 update 方法。