如何覆盖 Python Jupyter 显示输出

How to overwrite Python Jupyter display output

我用 ipywidgets 创建了一个小表单。示例代码可以是 运行 in Jupyter 或 Google colab.

每次填写表单并单击按钮时,都会将一行添加到数据框中。随后显示数据框。

我的问题是输出显示新的更新数据框在旧数据框之上。我想要的是新的显示输出覆盖旧的。 See image description here.

import ipywidgets as widgets
from ipywidgets import HBox, Label
from ipywidgets import Layout, Button, Box, FloatText, Textarea, Dropdown, Label, IntSlider
import time
import pandas as pd

#Create DF
df = df = pd.DataFrame(columns = ['Dropdown_column', 'Float_column'])
df

# Layout
form_item_layout = Layout(
    display='flex',
    flex_flow='row',
    justify_content='space-between',
)


button_item_layout = Layout(
    display='flex',
    flex_flow='row',
    justify_content='center',
    padding = '5%'
)

# Dropdown item

drop_down_input = 'Dropdown_input_1'

drop_down = widgets.Dropdown(options=[('Dropdown_input_1', 'Dropdown_input_1'), ('Dropdown_input_2','Dropdown_input_2'), ('Dropdown_input_3', 'Dropdown_input_3')])

def dropdown_handler(change):
    global drop_down_input
    print('\r','Dropdown: ' + str(change.new),end='')
    drop_down_input = change.new  
drop_down.observe(dropdown_handler, names='value')

# FloatText item

float_input = 0

FloatText = widgets.FloatText()

def IntText_handler(change):
    global float_input
    print('\r','Float text:' + str(change.new),end='')
    float_input = change.new 
FloatText.observe(IntText_handler, names='value')



# Button

button = widgets.Button(description='Add row to dataframe')
out = widgets.Output()
def on_button_clicked(b):
    global df
    button.description = 'Row added'
    time.sleep(1)
    with out:
      new_row = {'Dropdown_column': drop_down_input, 'Float_column': float_input}
      df = df.append(new_row, ignore_index=True)
      button.description = 'Add row to dataframe'
      display(df)
button.on_click(on_button_clicked)

# Form items

form_items = [         
    Box([Label(value='Dropdown'),
         drop_down], layout=form_item_layout),
    Box([Label(value='FloatText'),
         FloatText], layout=form_item_layout),
    Box([Label(value=''), button],
        layout=button_item_layout),    
]

form = Box(form_items, layout=Layout(
    display='flex',
    flex_flow='column',
    border='solid 1px',
    align_items='stretch',
    width='30%',
    padding = '1%'
))
display(form)
display(out)

我已经尝试将 print() 函数与“/r”结合使用并更改代码的#button 部分。 变化:

display(df)

print('\r',str(df), end='')

print(str(df), end='\r')

但这也不行。

有人知道该怎么做吗?

\r 仅适用于单行普通文本,但 df 不显示为普通文本(并且它不是单行),而是显示为 HTML 代码。

您必须使用 out.clear_output() 删除以前的内容。

   with out:
      new_row = {'Dropdown_column': drop_down_input, 'Float_column': float_input}
      df = df.append(new_row, ignore_index=True)
      button.description = 'Add row to dataframe'

      out.clear_output()  # <---

      display(df)

您可以在文档中查看有关 out.clear_output() 的更多信息:
Output widgets: leveraging Jupyter’s display system