多个依赖小部件和函数

2024-05-18 18:57:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种方法来集成下面问题中作为示例提供的代码,在这里我可以添加多个可以一次动态更新的函数:

Multiple dependent widgets (dropdown menu) on Jupyter notebook

以修订后的示例为例,我想在另一个函数中定义total,当动态更新时,可以使用if __name__ == '__main__':。我可以通过向print_city函数添加代码来添加许多计算和新的小部件,但我想学习更好的方法,如果代码中有@interaction,我无法理解这是如何工作的

from ipywidgets import interact, Dropdown

geo = {'USA':['CHI','NYC'],'Russia':['MOW','LED']}
priceW = Dropdown(options = [105, 100, 80])
rateW = FloatText(200)

countryW = Dropdown(options = geo.keys())
cityW = Dropdown(options = geo[countryW.value])
districtW = Dropdown()

@interact(country=countryW, city=cityW, price=priceW, rate=rateW)
def print_city(country, city, price, rate):
    cityW.options = geo[country]
    priceW = price
    rateW = rate
    total = rate*price
    print('Total: ', total)

我正在寻找这样的东西,如果有意义的话:

from ipywidgets import interact, Dropdown

geo = {'USA':['CHI','NYC'],'Russia':['MOW','LED']}
priceW = Dropdown(options = [105, 100, 80])
rateW = FloatText(200)

def main():
    .....
    


countryW = Dropdown(options = geo.keys())
cityW = Dropdown(options = geo[countryW.value])
districtW = Dropdown()

@interact(country=countryW, city=cityW, price=priceW, rate=rateW)
def print_city(country, city, price, rate):
    cityW.options = geo[country]
    priceW = price
    rateW = rate
    
def totale():
    total = rate*price
    print('Total: ', total)
    

if __name__ == '__main__':
    main()  

Tags: cityratemaincountrypriceinteractgeooptions

热门问题