How to send extra **Kwargs to event click method of an ipyvuetify button

366 Views Asked by At

I am using ipyvuetify to create a dashboard including several buttons.

here the code for one of them:

import ipyvuetify as vue
from ipywidgets import Output

out = Output()
mybtn = vue.Btn(color='primary', children=['Run'])

def btn_method(widget, event, data):
    with out:
        print('btn was clicked')
          
mybtn.on_event('click', btn_method)

display(mybtn,out)

My problem is that when clicking a button the actions carried out depend on some varaibles. The question is how can I send to the button extra data, i.e. a dictionary of data.

Pseudo code:

import ipyvuetify as vue
from ipywidgets import Output
out = Output()
mybtn = vue.Btn(color='primary', children=['Run'])
# t followoing does not work, nor it gives an error:
def btn_method(widget, event, data, **kwargs):
    with out:
        print('btn was clicked')
        print(len(kwargs))
    if myvar==4:
        #do this
        pass
    else:
        #do that
        pass
             
mybtn.on_event('click', btn_method, kwargs={'myvar':4})

display(mybtn,out)

Of course the error is: on_event() got an unexpected keyword argument 'kwargs', i.e. you are not supposed to send other vars into the on_event method.

Any idea how to proceed?

thanks

2

There are 2 best solutions below

0
Christoph Weiss-Schaber On BEST ANSWER

you can simply set your dictionary as an additional attribute of the button object and read it inside the callback function.

mybtn = vue.Btn(color='primary', children=['Run'])

def btn_method(widget, event, data):
    with out:
        print('btn was clicked')
        print(widget.kwargs)
    if widget.kwargs['myvar']==4:
        #do this
        pass
    else:
        #do that
        pass
             
mybtn.on_event('click', btn_method)
mybtn.kwargs={'myvar':4}
2
mguijarr On

One possibility is to use functools.partial to make a new callback function on-the-fly, that would have the extra args you want to pass already defined:

import functools

def btn_method(widget, event, data, **kwargs):
    with out:
        print('btn was clicked')
        print(len(kwargs))
    if kwargs.get("myvar")==4:
        #do this
        pass
    else:
        #do that
        pass
             
mybtn.on_event('click', functools.partial(btn_method, myvar=4))

(untested code)