我想使用widgets.Text()来指定可以传递给API请求的多个变量(年,月,日)。
根据this question的答案,我能够将输入从单个文本框成功保存到单个变量。但是我想同时显示多个文本框并将其输入值保存到三个不同的输出变量中。我不确定如何从给出的例子中推广出来。
此代码适用于单个变量:
# 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)
如果这还不够清楚,请道歉!我可以根据需要澄清。非常感谢任何指导。谢谢!
答案 0 :(得分:1)
通过调整this question的说明,我能够做我想做的事。我的代码如下,供参考:
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]))