2

我想使用 widgets.Text() 来指定可以传递到 API 请求中的多个变量(年、月、日)。

根据对这个问题的回答,我能够成功地将输入从单个文本框保存到单个变量。但我想同时显示多个文本框并将它们的输入值保存到三个不同的输出变量中。我不确定如何从给出的示例中进行概括。

此代码适用于单个变量:

# Create text widget for output
year_output = widgets.Text()

# Create text widget for input
year_input = widgets.Text(
    placeholder="example '2017'",
    description='Year:',
    disabled=False
    )

# Define function to bind value of the input to the output variable 
def bind_input_to_output(sender):
    year_output.value = year_input.value

# Tell the text input widget to call bind_input_to_output() on submit
year_input.on_submit(bind_input_to_output)

# Display input text box widget for input
display(year_input)

我希望能够尽可能高效地做这样的事情:

year_output = widgets.Text()
month_output = widgets.Text()
day_output = widgets.Text()

year_input = widgets.Text(
    placeholder="example '2017'",
    description='Year:',
    disabled=False
    )

month_input = widgets.Text(
    placeholder="example '04'",
    description='Month:',
    disabled=False
    )

day_input = widgets.Text(
    placeholder="example '30'",
    description='Day:',
    disabled=False
    )

#make this a generic function so that I don't have to repeat it for every input/output pair
def bind_input_to_output(sender): #what is 'sender'?
    output_var.value = input_var.value

year_input.on_submit(bind_input_to_output)
mont_input.on_submit(bind_input_to_output)
day_input.on_submit(bind_input_to_output)

display(year_input)
display(month_input)
display(day_input)

抱歉,如果这不够清楚!我可以根据需要澄清。非常感谢任何指导。谢谢!

4

1 回答 1

3

通过调整这个问题的说明,我能够做我想做的事。我的代码如下,供参考:

import ipywidgets as widgets
from IPython.display import display

class date_input():
    def __init__(self, 
                 year = "e.g. '2017'", 
                 month = "e.g. '05'", 
                 day = "e.g. '21'"
                ):
        self.year = widgets.Text(description = 'Year',value = year)
        self.month = widgets.Text(description = 'Month',value = month)
        self.day = widgets.Text(description = 'Day',value = day)        
        self.year.on_submit(self.handle_submit)
        self.year.on_submit(self.handle_submit)
        self.year.on_submit(self.handle_submit)
        display(self.year, self.month, self.day)

    def handle_submit(self, text):
        self.v = text.value
        return self.v

print("enter the year, month and day above, then press return in any field")
f = date_input()

要查看输出,请在下一个单元格中运行:

print("Date input captured: " + "/".join([f.year.value, f.month.value, f.day.value]))
于 2017-05-04T21:49:24.577 回答