没有合适的资源?快使用搜索试试~ 我知道了~
首页python模拟事件触发机制详解
资源详情
资源评论
资源推荐

python模拟事件触发机制详解模拟事件触发机制详解
主要为大家详细介绍了python模拟事件触发机制的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参
考一下
本文实例为大家分享了python模拟事件触发机制的具体代码,供大家参考,具体内容如下
EventManager.py
# -*- encoding: UTF-8 -*-
# 系统模块
from queue import Queue, Empty
from threading import *
class EventManager:
def __init__(self):
"""初始化事件管理器"""
# 事件对象列表
self.__eventQueue = Queue()
# 事件管理器开关
self.__active = False
# 事件处理线程
self.__thread = Thread(target = self.__Run)
# 这里的__handlers是一个字典,用来保存对应的事件的响应函数
# 其中每个键对应的值是一个列表,列表中保存了对该事件监听的响应函数,一对多
self.__handlers = {} # {事件类型:[处理事件的方法]}
def __Run(self):
"""引擎运行"""
while self.__active == True:
try:
# 获取事件的阻塞时间设为1秒
event = self.__eventQueue.get(block = True, timeout = 1)
self.__EventProcess(event)
except Empty:
pass
def __EventProcess(self, event):
"""处理事件"""
# 检查是否存在对该事件进行监听的处理函数
if event.type_ in self.__handlers:
# 若存在,则按顺序将事件传递给处理函数执行
for handler in self.__handlers[event.type_]:
handler(event)
def Start(self):
"""启动"""
# 将事件管理器设为启动
self.__active = True
# 启动事件处理线程
self.__thread.start()
def Stop(self):
"""停止"""
# 将事件管理器设为停止
self.__active = False
# 等待事件处理线程退出
self.__thread.join()
def AddEventListener(self, type_, handler):
"""绑定事件和监听器处理函数"""
# 尝试获取该事件类型对应的处理函数列表,若无则创建
try:
handlerList = self.__handlers[type_]
except KeyError:
handlerList = []
self.__handlers[type_] = handlerList
# 若要注册的处理器不在该事件的处理器列表中,则注册该事件
if handler not in handlerList:
handlerList.append(handler)
def RemoveEventListener(self, type_, handler):
"""移除监听器的处理函数"""
#读者自己试着实现







安全验证
文档复制为VIP权益,开通VIP直接复制

评论0