gpt4 book ai didi

python - 使用 Ipython ipywidget .Text() 创建多个变量

转载 作者:太空宇宙 更新时间:2023-11-03 15:17:43 24 4
gpt4 key购买 nike

我想使用 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)

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

最佳答案

通过调整 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]))

关于python - 使用 Ipython ipywidget .Text() 创建多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43744999/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com