Python EasyGUI multchoicebox多选项IF判断逻辑失效求助
Let's break down why your code isn't triggering the "Correct!" message, then fix it properly.
The Core Problem
First, you need to remember that easygui.multchoicebox() returns a list of selected options, not a single string. For example, if the user picks "Correct" and "Also Correct", choice will be something like ["Correct", "Also Correct"] (the order might vary based on how the user clicks).
Your original condition has two big issues:
- You're comparing a list (
choice) directly to a single string (fieldnames[1]), which will never be true. - The
and fieldnames[2]part doesn't check if that option is selected—sincefieldnames[2]is a non-empty string, it always evaluates toTruein a boolean check. So your condition effectively becomesFalse and True, which is alwaysFalse.
The same problem applies to your second attempt: comparing a list to a string will never work, and and "Also Correct" doesn't validate that the option is actually selected.
Fixes for Different Scenarios
We'll cover two common use cases—pick the one that matches your needs.
Scenario 1: User must select exactly "Correct" and "Also Correct" (no more, no less)
Use a set comparison to ignore the order of selections (since users might click the options in any order):
import easygui fieldnames = ["Incorrect", "Correct", "Also Correct"] choice = easygui.multchoicebox("Pick an option.", "", fieldnames) # Handle the case where the user clicks "Cancel" (returns None) if choice is not None and set(choice) == {"Correct", "Also Correct"}: easygui.msgbox('Correct!') else: easygui.msgbox('Incorrect')
Scenario 2: User just needs to select both "Correct" and "Also Correct" (can select other options too)
Check if both options are present in the selected list:
import easygui fieldnames = ["Incorrect", "Correct", "Also Correct"] choice = easygui.multchoicebox("Pick an option.", "", fieldnames) if choice is not None and "Correct" in choice and "Also Correct" in choice: easygui.msgbox('Correct!') else: easygui.msgbox('Incorrect')
Extra Note
We added choice is not None to handle cases where the user clicks the "Cancel" button in the multchoicebox—this prevents a TypeError if you try to check membership or convert None to a set.
内容的提问来源于stack exchange,提问作者John Collins

