Skip to content
Advertisement

Python ipywidgets – empty widget that can be filled inside a function

Let’s say I have a dropdown widget with some numbers and a floatext widget with some other numbers. I would like to define a widget that takes an empty parameter and can be dynamically filled with the calculation made inside the function which in this case would be mW.

I could do it by not defining the mW widget and returning this inside the function but I was hoping for another way.

dW = Dropdown(options = [1, 2, 3, 4])
rW = FloatText(200)
mW = ...... empty widget to be filled with the calculation made inside the fuction

@interact(D=dW, R=rW, mW=M)
def print_p(D, R):
    dW = D
    rW = R
    mW = D*R

My expected outcome would be the below with 400 or another number calculated dynamically filled in the M box.

enter image description here

Advertisement

Answer

For:

“Defining a widget that takes an empty parameter and can be dynamically filled with the calculation made inside the function”

You can simply use a FloatText widget with no parameters, and then setting the value inside the function; as follows:

from __future__ import print_function
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets

dW = widgets.Dropdown(options=['2', '1'])
rW = widgets.FloatText(200)
mW = widgets.FloatText()             #empty widget

@interact(D=dW, R=rW, M= mW)

def print_p(D, R, M):
    dW = D
    rW = R
    mW.value = int(dW)*int(rW)      #now i set the value of the empty widget

Then, for dinamically checking the value of mW, you can use the threading library:

import threading

For any doubt:

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement