本文实例为大家分享了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: