Skip to content

Instantly share code, notes, and snippets.

@bendichter
Created April 4, 2020 19:02
Show Gist options
  • Save bendichter/ef185a1fb4784e12da74a964a63c898a to your computer and use it in GitHub Desktop.
Save bendichter/ef185a1fb4784e12da74a964a63c898a to your computer and use it in GitHub Desktop.
Example of how to thread a plotting widget so that only the latest command is run
from ipywidgets import VBox, Button, HTML
import time
from threading import Thread
from queue import Queue
class MyWidget(VBox):
def __init__(self):
super(MyWidget, self).__init__()
self.button = Button(description='next')
self.out = HTML('start')
self.button.on_click(self.handler)
self.children = [self.button, self.out]
self.count = 0
self.plotting_thread = None
self.queue = Queue(maxsize=1)
self.plotting_thread = Thread(target=self.plotter)
self.plotting_thread.daemon = True
self.plotting_thread.start()
self.command_counter = 0
def plotter(self):
while True:
command_counter = self.queue.get()
self.move_up()
print('command: {}'.format(command_counter))
self.queue.task_done()
def move_up(self):
time.sleep(5)
self.count += 1
self.out.value = str(self.count)
def handler(self, change):
self.command_counter += 1
if self.queue.full():
self.queue.get()
self.queue.task_done()
self.queue.put(self.command_counter)
@bendichter
Copy link
Author

To test, run this in a notebook. Then click "next" a bunch of times in a row. The code should only execute twice- the firs time and the last time the button is pressed (as indicated by the command count).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment