Clear output widget using onclick Button event - Python

我的未来我决定 提交于 2020-01-22 02:21:12

问题


I am working on a Jupyter Notebook in which I am using a button created with ipywidgets to display a df when clicking on it. For this I am using the following code:

import ipywidgets as widgets
import numpy as np 

vartest = 0

Button = widgets.Button(description='Search', disabled=False, button_style='info', tooltip='Search')
display(Button)

def whenclick2(b):
    global df

    if vartest==0:
        df = pd.DataFrame(np.arange(5))


        class displayDF(object):
            def _create_widgets(self):
                self.button = Button
                self.button.on_click(self._on_button_clicked) # define which function to run when cliked

            def _on_button_clicked(self, change):
                self.out.clear_output() # clean previous outptu (I think ). Not working
                with self.out:# using self.out (the output widget) do the display
                    display(df) #aqui es donde digo que haga display del dataframe que es la variable self.file1

            def display_widgets(self):
                self._create_widgets() # calls the creation of the widgets
                self.out = widgets.Output()  # this is the output widget in which the df is displayed
                display(widgets.VBox([self.out])) # controls layout of widget position  

            def get_df_objects(self):
                return self.df_objects

    # Run class and store output in something
    something = displayDF()
    # output the display
    something.display_widgets()

    #return df    

Button.on_click(whenclick2)

The code does the job and displays the df however, when clicking again it seems the clear_output() code is not working. Instead of removing the previous output and then deliver the a new, it just prints the second one below the first, etc.

This code is an adaptation coming from this post - Python onclick button widget return object . In that example, he manages to make it work but I am trying to adapt it to my case and I cannot reproduce that behabiour. What am I missing?

来源:https://stackoverflow.com/questions/59719207/clear-output-widget-using-onclick-button-event-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!