我想在按下ipython小部件按钮时递增计数器。我能够在下面的代码中使用global
来解决这个问题,但有什么更好的方法呢?
import ipywidgets as widgets
from IPython.display import display
count = 0
w = widgets.Button(description='Click me')
w.on_click(plusone)
display(w)
def plusone(w):
global count
count +=1
答案 0 :(得分:1)
使你的计数器成为一个对象并让你的回调将计数器对象作为参数。
class Counter:
def __init__(self, initial=0):
self.value = initial
def increment(self, amount=1):
self.value += amount
return self.value
def __iter__(self, sentinal=False):
return iter(self.increment, sentinal)
然后你可以只传递这个对象的实例..
import ipywidgets as widgets
from functools import partial
from IPython.display import display
def button_callback(counter, w):
counter.increment()
counter = Counter()
w = widgets.Button(description='Click me')
w.on_click(partial(button_callback, counter))
display(w)
#... sometime later
if counter.value > SOME_AMOUNT:
do_stuff()