简体   繁体   中英

Unselecting selected option in combobox

I wrote a function which implements something like when user selects 1st option in Combobox this option shouldn't be available in rest comboboxes. It's working but when I choose all options after another no option is available to select.

I want to make it working like when user selects for example 1st option in combobox, this option isn't available in rest comboboxes but when user unselects this 1st option, this option is available again everywhere.

Here's the code which I tried to implement and I have no idea how can I repair this code.

toChoose = [
    "Option 1",
    "Option 2",
    "Option 3",
    "Option 4",
    "Option 5",
    "Option 6",
    "Option 7"
]

box = Combobox(self, values=toChoose, state="readonly")
box2 = Combobox(self, values=toChoose, state="readonly")
box3 = Combobox(self, values=toChoose, state="readonly")
box4 =  Combobox(self, values=toChoose, state="readonly")

selected = set()


def on_select(event):
    value = event.widget.get()

    if value in selected:
        return

    selected.add(value)

    values = [val for val in toChoose if val not in selected]
    box.configure(values=values)
    box2.configure(values=values)
    box3.configure(values=values)
    box4.configure(values=values)

    box['values'] = [x for x in toChoose if x not in selected]
    box2['values'] = [x for x in toChoose if x not in selected]
    box3['values'] = [x for x in toChoose if x not in selected]
    box4['values'] = [x for x in toChoose if x not in selected]


box.bind("<<ComboboxSelected>>", on_select)
box2.bind("<<ComboboxSelected>>", on_select)
box3.bind("<<ComboboxSelected>>", on_select)
box4.bind("<<ComboboxSelected>>", on_select)

You need to get all the selected values in those comboboxes, then the available values of a combobox are its selected value (if any) and values that are not in the selected values:

def on_select(event):
    combolist = (box, box2, box3, box4)
    # get all the selected values
    selected = [cb.get() for cb in combolist if cb.get()]
    # go through each combobox
    for cb in combolist:
        # available values = (self selected value) + (values not in selected)
        cb['values'] = [v for v in toChoose if cb.get() == v or v not in selected]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM