在 select 多个 ipywidgets 中保留顺序
Retain order in select multiple ipywidgets
我有一个 SelectMultiple IpyWidgets。
import ipywidgets as widgets
d = widgets.SelectMultiple(
options=['Apples', 'Oranges', 'Pears',"Mango"],
#rows=10,
description='Fruits',
disabled=False
)
原帖:
print (list(d.value))
['Apples', 'Mango']
无论我 select 的顺序如何,OP 中的顺序始终与选项列表中的顺序相同。例如,即使我 select Mango first and then Apple
OP 仍然是给定的。
您需要一种变通方法来捕获点击顺序,与描述的类似 :
import ipywidgets as widgets
d = widgets.SelectMultiple(
options=['Apples', 'Oranges', 'Pears',"Mango"],
description='Fruits',
disabled=False
)
foo = []
def on_change(change):
if change['type'] == 'change' and change['name'] == 'value':
for elem in change['new']:
if elem not in foo:
foo.append(elem)
for elem in foo:
if elem not in change['new']:
foo.remove(elem)
d.observe(on_change)
d
foo 只是一个占位符。现在,如果您单击 'Mango',然后单击 'Apple',您将得到:
print('values:', d.value) # values: ('Apples', 'Mango')
print('click_order:', foo) # click_order: ['Mango', 'Apples']
我有一个 SelectMultiple IpyWidgets。
import ipywidgets as widgets
d = widgets.SelectMultiple(
options=['Apples', 'Oranges', 'Pears',"Mango"],
#rows=10,
description='Fruits',
disabled=False
)
原帖:
print (list(d.value))
['Apples', 'Mango']
无论我 select 的顺序如何,OP 中的顺序始终与选项列表中的顺序相同。例如,即使我 select Mango first and then Apple
OP 仍然是给定的。
您需要一种变通方法来捕获点击顺序,与描述的类似
import ipywidgets as widgets
d = widgets.SelectMultiple(
options=['Apples', 'Oranges', 'Pears',"Mango"],
description='Fruits',
disabled=False
)
foo = []
def on_change(change):
if change['type'] == 'change' and change['name'] == 'value':
for elem in change['new']:
if elem not in foo:
foo.append(elem)
for elem in foo:
if elem not in change['new']:
foo.remove(elem)
d.observe(on_change)
d
foo 只是一个占位符。现在,如果您单击 'Mango',然后单击 'Apple',您将得到:
print('values:', d.value) # values: ('Apples', 'Mango')
print('click_order:', foo) # click_order: ['Mango', 'Apples']