首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >在IPython小部件中动态添加和删除列表项

在IPython小部件中动态添加和删除列表项
EN

Stack Overflow用户
提问于 2020-11-19 21:37:20
回答 1查看 391关注 0票数 1

我正在尝试使用ipywidgets在Ipython Jupyter Notebook中实现一个基本的待办事项列表应用。

我可以很容易地实现将项目添加到我的列表中的功能,但是,如果单击“删除”按钮,我无法正确处理现有项目的删除。整个代码在单个单元中运行。

代码语言:javascript
代码运行次数:0
运行
复制
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的定义更新如下:

代码语言:javascript
代码运行次数:0
运行
复制
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小部件来处理这种“反应式”编程的最佳方式是什么?

EN

回答 1

Stack Overflow用户

发布于 2020-11-19 21:52:00

更新completed_sentence的定义似乎可以完成这项工作。但它仍然是一个谜,为什么原始的定义不起作用。

代码语言:javascript
代码运行次数:0
运行
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64912840

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档