我正在尝试使用ipywidgets
在Ipython Jupyter Notebook中实现一个基本的待办事项列表应用。
我可以很容易地实现将项目添加到我的列表中的功能,但是,如果单击“删除”按钮,我无法正确处理现有项目的删除。整个代码在单个单元中运行。
import ipywidgets as widgets
from ipywidgets import VBox, HBox, Text, Button
from IPython.display import display
todo = []
def completed_sentence(sentence):
""" To display existing notes with a 'Remove' button """
sentenceField = Text(value=sentence)
removeButton = Button(description='Remove',
button_style='danger')
return HBox([sentenceField, removeButton])
def render_sentences(_):
""" To update the view """
global a,b
if a.value != '':
todo.append(a.value)
a.value = ''
todoWidget.children = tuple\
([VBox([VBox([completed_sentence(each)
for each in todo]),
HBox([a, b])])])
# Setting up a basic view- with an empty field and a button
a = widgets.Text(value='')
b = widgets.Button(description='Add')
b.on_click(render_sentences)
todoWidget = widgets.HBox([a, b])
display(todoWidget)
现在,为了能够删除句子,我将函数completed_sentence
的定义更新如下:
def completed_sentence(sentence):
""" To display existing notes """
def remove_sentence(_):
global render_sentences
try:
if todo.index(sentenceField.value) >= 0:
todo.remove(sentenceField.value)
render_sentences()
except:
return
sentenceField = Text(value=sentence)
removeButton = Button(description='Remove', button_style='danger')
removeButton.on_click(remove_sentence)
return HBox([sentenceField, removeButton])
但是现在,这有一个问题,它对render_sentences
的调用被忽略了!如果您愿意,使用Ipython小部件来处理这种“反应式”编程的最佳方式是什么?
发布于 2020-11-19 13:52:00
更新completed_sentence
的定义似乎可以完成这项工作。但它仍然是一个谜,为什么原始的定义不起作用。
def completed_sentence(sentence):
def remove_sentence(_):
global render_sentences
try:
if todo.index(sentenceField.value) >= 0:
todo.remove(sentenceField.value)
except:
pass
render_sentences(_)
sentenceField = Text(value=sentence)
removeButton = Button(description='Remove', button_style='danger')
removeButton.on_click(remove_sentence)
sentence_view = HBox([sentenceField, removeButton])
return sentence_view
https://stackoverflow.com/questions/64912840
复制