请考虑以下示例:
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
,bindings本身是异步的。
但是,如果你试图坚持使用asyncio
它也是可能的,但首先让我们考虑一下你的尝试。
你的第一次尝试显然是失败,因为你试图将spam
称为通用函数,当它是coroutine
时。你的其他尝试比第一次尝试更正确,但是await coroutine
或yield from coroutine
可以用来从另一个coroutine开始一个coroutine,所以它再次失败。
因此,开始这种野兽的正确方法是使用自解释方法ensure_future
(或旧的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))
此外,我认为值得提及this问题,因为你使用update
方法。