【问题标题】:Ipywidgets not interacting in "while True" loopIpywidgets 不在“while True”循环中交互
【发布时间】:2020-09-01 00:08:39
【问题描述】:

1)这是我试图运行的代码 sn-p。主要思想是,我希望 ipywidgets 是交互式的,同时不断地从数据源中获取数据。并且使用 while 循环以特定间隔更新数据。目标是使用 @interact 函数通过更改要考虑的主成分 (PC) 的数量以交互方式绘制主成分。 此外,它在没有 while 循环的情况下运行得非常好,也就是说,当我们不考虑使用 while 循环对数据集进行自动更新时。但是当我包含 while 循环时,它不处理小部件的交互性(即 PC 数量的交互)。 我的感觉是,由于某些执行问题,“while True”循环不会让 ipywidget 的交互发生。

2) 我也研究了线程,但我不确定如何使用 functools(select_data) 中的函数,使用 threading.Thread 调用。

任何形式的帮助将不胜感激。谢谢

def data_import_date(start_date,end_date):
    end_date1=end_date.strftime('%Y-%m-%dT%H:%M:%S')
    start_date=pd.Timestamp(start_date)
    end_date=pd.Timestamp(end_date1)

    button=widgets.Button(description='Pull Data')
    button.on_click(functools.partial(select_data,rs_=[start_date,end_date]))

    vbox=widgets.VBox([button])
    display(vbox,out)


def select_data(b,rs_):
#     clear_output()
    start_date=rs_[0]
    end_date1=rs_[1]
    print("Data pulling started")

    with out:
        clear_output()
        seeq_login() 
        [item1,item2]=query_seeq_for_data()
        i=0
        while True:
            end_date=end_date1.strftime('%Y-%m-%dT%H:%M:%S')
            print("Start & End date: ",start_date,end_date)
            if i==0:
                [X_data,Y_data]=pull_data(item1,item2,start_date,end_date)
            else:
                [X_data_live,Y_data_live]=pull_data(item1,item2,start_date,end_date)
                X_data=X_data.append(X_data_live)
                Y_data=Y_data.append(Y_data_live)
            print("Data pulling completed.\nNow you're ready for your analysis")

            clear_output()
            [X_train,X_test,Y_train,Y_test]=train_test(X_data,Y_data)

            [Xp_train,components,explained_variance_ratio,_,_]=apply_PCA(X_train,X_test)
            plot_PC_variance(X_data,explained_variance_ratio)
            plot_PC(X_data,components)

            time.sleep(20)
            start_date=end_date
            end_date1=end_date1+datetime.timedelta(days=1)
            i+=1



  a=interact(data_import_date,
           start_date=widgets.DatePicker(value=pd.to_datetime(start_date)),
           end_date=widgets.DatePicker(value=pd.to_datetime(end_date)))


def plot_PC(X_data,components):
    Np_comp=(1,len(X_data.columns),1)
    @interact
    def principal_components(PC1=Np_comp,PC2=Np_comp):
        fig,ax=plt.subplots(1,1,figsize=(10,10))
        plt.figure(5)
        print(PC1, PC2)

        ax.set_xlabel("Principal Component {}".format(PC1), fontsize=14)
        ax.set_ylabel("Principal Component {}".format(PC2), fontsize=14)
        ax.set_title("Principal components {0} & {1}".format(PC1,PC2), fontsize=(20))
        ax.scatter(components[:,PC1],components[:,PC2])

【问题讨论】:

  • 你是对的,while 循环阻止了小部件的任何更改。您需要查看异步小部件的实现:ipywidgets.readthedocs.io/en/latest/examples/…
  • @ac24,你能详细说明一下这方面的实现吗?我已经多次浏览文档,但在更改代码时遇到了麻烦。

标签: while-loop jupyter-notebook python-3.5 ipywidgets voila


【解决方案1】:

一个相当基本的示例,展示了如何在轮询小部件更改的同时运行循环,但这并不是我真正的专业领域。

在打印值时拖动滑块,您应该会看到打印值的变化以反映当前滑块的位置。


import threading
from IPython.display import display
import ipywidgets as widgets
import time
float_val = widgets.FloatSlider()
display(float_val)

def work(progress):
    total = 10
    for i in range(total):
        time.sleep(1)
        print(float_val.value)

thread = threading.Thread(target=work, args=(progress,))

thread.start()

【讨论】:

  • 我了解您试图解决的问题。但是,如果您查看我的代码,我会对使用 threading.Thread 中的目标函数作为选择数据函数感兴趣。但它已经使用 button.on_click 调用了吗?
猜你喜欢
  • 2016-12-03
  • 1970-01-01
  • 2021-10-19
  • 2012-03-26
  • 1970-01-01
  • 2020-03-23
  • 2017-07-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多