Jupyter ipywidgets 滑块在更改时发出 HTTP 请求
以下 Jupyter 单元格使用 ipywidgets 显示 0.0 … 1.0 的滑块,并在更改时向 http://10.1.2.3.4/api/set-power?power=[滑块值] 发出 HTTP 请求。
ipywidgets_slider_set_power.py
import ipywidgets as widgets
import requests
from IPython.display import display
# Define the slider widget
slider = widgets.FloatSlider(
value=0.5, # Initial value
min=0.0, # Minimum value
max=1.0, # Maximum value
step=0.01, # Step size
description='Slider:'
)
# Define a function to handle slider changes
def on_slider_change(change):
slider_value = change['new']
# Define the API URL with the slider value
api_url = f'http://10.1.2.3.4/api/set-power?power={slider_value}'
print(api_url)
# Make the HTTP request
try:
response = requests.get(api_url)
response.raise_for_status() # Raise an exception for HTTP errors
print(f'Successfully set power to {slider_value}')
except requests.exceptions.RequestException as e:
print(f'Error: {e}')
# Attach the slider change handler to the slider widget
slider.observe(on_slider_change, names='value')
# Display the slider widget in the notebook
display(slider)If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow