问题描述
我在实现 “Debounce” 装饰器并将其与 matplotlib
和 ipywidget IntSlider
结合时遇到了一些问题。
以下是 the official ipywidgets documentation 建议的去抖动代码:
import asyncio
class Timer:
def __init__(self,timeout,callback):
self._timeout = timeout
self._callback = callback
self._task = asyncio.ensure_future(self._job())
async def _job(self):
await asyncio.sleep(self._timeout)
self._callback()
def cancel(self):
self._task.cancel()
def debounce(wait):
""" Decorator that will postpone a function's
execution until after `wait` seconds
have elapsed since the last time it was invoked. """
def decorator(fn):
timer = None
def debounced(*args,**kwargs):
nonlocal timer
def call_it():
fn(*args,**kwargs)
if timer is not None:
timer.cancel()
timer = Timer(wait,call_it)
return debounced
return decorator
这是我用来实现 @debounce
的代码,同时使用 widgets.IntSlider
更新绘制的图形。
def plot():
@debounce(0.1)
def f(i):
fig,ax = plt.subplots()
ax.plot([i,i*i],[i,0 ],[0,i*2])
ax.set_title(i)
interact(f,i=IntSlider(min=0,max=10,value=4))
当我在 Jupyter Notebook 的单元格中调用函数 plot()
时,当我移动滑块而不是更新相同的 fig,ax
时,会绘制多个图形。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)