Rich Signell
Rich Signell

Reputation: 16455

Incrementing a counter using ipython widgets

I would like to increment a counter when an ipython widget button is pressed. I was able to get this to work using global in the code below, but what is a better way to do it?

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

Upvotes: 2

Views: 2274

Answers (1)

Chad S.
Chad S.

Reputation: 6631

Make your counter an object and have your callback take the counter object as an argument.

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)

Then you can just pass instances of this object around..

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()

Upvotes: 4

Related Questions