如何发送额外的 **Kwargs 到 ipyvuetify 按钮的事件点击方法
How to send extra **Kwargs to event click method of an ipyvuetify button
我正在使用 ipyvuetify 创建一个包含多个按钮的仪表板。
这里是其中之一的代码:
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)
我的问题是单击按钮时执行的操作取决于某些变量。问题是如何向按钮发送额外数据,即数据字典。
伪代码:
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)
当然错误是:on_event() 得到了一个意外的关键字参数 'kwargs',即你不应该将其他变量发送到 on_event 方法。
知道如何进行吗?
谢谢
一种可能是使用functools.partial
进行新的回调
运行中的函数,你想要传递的额外参数已经定义好了:
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))
(未经测试的代码)
您可以简单地将字典设置为按钮对象的附加属性,并在回调函数中读取它。
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}
我正在使用 ipyvuetify 创建一个包含多个按钮的仪表板。
这里是其中之一的代码:
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)
我的问题是单击按钮时执行的操作取决于某些变量。问题是如何向按钮发送额外数据,即数据字典。
伪代码:
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)
当然错误是:on_event() 得到了一个意外的关键字参数 'kwargs',即你不应该将其他变量发送到 on_event 方法。
知道如何进行吗?
谢谢
一种可能是使用functools.partial
进行新的回调
运行中的函数,你想要传递的额外参数已经定义好了:
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))
(未经测试的代码)
您可以简单地将字典设置为按钮对象的附加属性,并在回调函数中读取它。
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}