1、使用场景
下拉菜单选项,单选或者多选
2、multiple参数
默认单选,multiple是True时支持多选
3、options参数
options参数详情:
- label:用户看到的选项的名称
- value:选项实际代表的value
- selected:bool类型(默认false),当是单选时,仅能有一个true。如果有多个true,那生效的将是最后一个selected是true的选项。如果全都是false,那默认选中第一个选项。
- disabled:bool类型(默认false),声明该选项是否能够可选。为True时选项置灰不能选择;为False时选项可选。
官方解释:
"label":(str) option label,
"value":(object) option value,
"selected":(bool, optional) whether the option is initially selected,
"disabled":(bool, optional) whether the option is initially disabled
3.1 label和value用法
3.1.1 label和value是同一个值
options=[“A”, “B”]
当options中的每个元素是一个值,那代表label和value是同一个值,且默认selected和disabled都是false。
import pywebio
from pywebio.input import select
from pywebio.output import put_text
def select1():
sel = select("选择选项:", options=["A", "B"])
put_text(f"你选择的是{sel}")
if __name__ == '__main__':
pywebio.start_server(select1, port=19000, debug=True, cdn=False, auto_open_webbrowser=False)
效果:
3.1.2 label和value不同
使用场景:可以理解为label是对value的重命名,单独为了用户使用起来更容易理解。例如,代码中参数用的值是英文或者数字,但是展示给用户的话,显示成中文更友好。
options=[[“A”, 0, False, True], [“B”, 1, True, False], [“C”, 2, False, False]]
def select2():
# options是列表
# mutiple是false,所以即使有多个选项selected是true,也只有一个会被默认选中(会取最后一个selected是true的选项)
sel = select("选择选项:", options=[["A", 0, False, True], ["B", 1, True, False], ["C", 2, False, False]])
put_text(f"你选择的是{sel}")
效果:
- A对应value是0
- B对应value是1
- C对应value是2
- 默认被选中的是B
- 选项A置灰不可选
options还可以是元组,效果同上
def select3():
# options是元组
# mutiple是false,所以即使有多个选项selected是true,也只有一个会被默认选中(会取最后一个selected是true的选项)
sel = select("选择选项:", options=[("A", 0, False, True), ("B", 1, True, False), ("C", 2, False, False)])
put_text(f"你选择的是{
sel}")
options还可以是字典,效果同上
def select4():
# options是字典
# mutiple是false,所以即使有多个选项selected是true,也只有一个会被默认选中(会取最后一个selected是true的选项)
sel = select("选择选项:", options=[{
"label": "A", "value": 0, "selected": False, "disabled": True},
{
"label": "B", "value": 1, "selected": True, "disabled": False},
{
"label": "C", "value": 2, "selected": False, "disabled": False}])
put_text(f"你选择的是{
sel}")
4、多选multiple=true
4.1 示例一
options中是single value,labe和value是同一个值。
在select方法中参数value=[“A”, “C”],默认选中A和C
def multiple_select():
sel = select("支持多选:", ["A", "B", "C"], multiple=True, value=["A", "C"])
put_text(f"你选择的是{
sel}")
效果:
- 默认选中A和C
- 结果为列表
4.2 示例二
options中不是single值,label和value值不相同。
def multiple_select():
sel = select("选择选项:", options=[("A", 0), ("B", 1), ("C", 2)], multiple=True)
put_text(f"你选择的是{
sel}")
效果:
- 初始时不会有选项被选中
- 选中结果是一个列表,有每个选中选项对应的value值