import re
import tkinter as tk
import asyncio
class HelloWorldGUI:
def __init__(self, master):
self.master = master
self.label = tk.Label(self.master)
self.label.pack()
self.hello_world_generator = self.hello_world()
def hello_world(self):
while True:
yield "Hello, World!"
def update_label(self):
try:
message = next(self.hello_world_generator)
except StopIteration:
self.hello_world_generator = self.hello_world()
message = next(self.hello_world_generator)
self.label["text"] = message
def start(self):
self.master.after(0, self.update_label)
self.master.mainloop()
def coroutine_decorator(func):
def wrapper(*args, **kwargs):
coro = func(*args, **kwargs)
next(coro)
return coro
return wrapper
@coroutine_decorator
def regex_coroutine(regex, target):
while True:
text = yield
matches = re.findall(regex, text)
for match in matches:
target.send(match)
def main():
root = tk.Tk()
gui = HelloWorldGUI(root)
regex = r"lo"
@coroutine_decorator
def print_match():
while True:
match = yield
print(f"Match found: '{match}'")
regex_coro = regex_coroutine(regex, print_match())
loop = asyncio.get_event_loop()
def schedule_regex_coroutine():
text = gui.label["text"]
regex_coro.send(text)
loop.call_later(1, schedule_regex_coroutine)
loop.call_soon(schedule_regex_coroutine)
gui.start()
if __name__ == "__main__":
main()
现在来详细分析下具体原理(结合代码看效果更佳):
[ol]
[/ol]
最终效果:生成一个GUI,中间有一个标签,显示Hello,World!的文本