3

I am trying to read a slider value in an infinite loop, but there is no print output. My goal is to control a robot with sliders, and the robot needs a constant stream of information even if the slider value doesn't change, thus the infinite while loop.

import ipywidgets as widgets
from IPython.display import display

slider = widgets.IntSlider()
display(slider)

while True:
    if slider.value != 0:
        print(slider.value)
buhtz
  • 10,774
  • 18
  • 76
  • 149
Kai Aeberli
  • 1,189
  • 8
  • 21
  • 1
    You need to look into asynchronous widget use. When your code is in the `while` loop, no updates to widgets get sent. https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Asynchronous.html – ac24 Apr 27 '20 at 06:52
  • great thanks, i managed to make it work with below library, in this case async didn't work for me. – Kai Aeberli May 10 '20 at 17:25

2 Answers2

2

I managed to make it work using this library: https://pypi.org/project/jupyter-ui-poll/

global slider_result_value
with ui_events() as poll:    
    # this unfreezes the ui and allows slider event handlers to fire
    # allowing sliders to update global variables which can be read out
    poll(10) # poll for 10 ui events

    do_something(slider_result_value)

Kai Aeberli
  • 1,189
  • 8
  • 21
1

This thread has saved me. The jupyter_ui_poll library works so well. It is exactly what I wanted.

Here is an example of using jupyter_ui_poll together with asyncio. It is a simple FM audio receiver app inside a Jupyter Notebook.

import nest_asyncio
nest_asyncio.apply()

import asyncio
from jupyter_ui_poll import ui_events

sdr.center_freq = 92_700_000 # an FM radio station running at 92.7MHz

async def streaming():
    it = 0
    async for data in sdr.stream():        
        # perform FM demodulation
        audio = fm_demodulation(data)

        # poll UI events
        with ui_events() as poll:
            poll(10)
            sdr.center_freq = slider.value

        # play the audio
        display(Audio(audio, autoplay=True, rate=48000, normalize=False))
        
        it = it + 1
        if it == it_num:
            break

slider = widgets.IntSlider()

display(slider)
    
asyncio.run(streaming())

I have omitted some implementation in the above code. Just to give an idea.

Godfly666
  • 63
  • 4