Python在一个函数中包含多个if语句

2024-05-19 15:20:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一名新的Python程序员。我希望用户从下拉菜单中选择三个项目(蓝色、紫色或黄色)中的一个,并根据他们的选择,在表单的另一部分显示一组卷。我试图在一个函数中编写多个“if”语句。在编写时,它将执行第一个“if”语句和“else”,但不会执行中间的两个“if”语句。我做错了什么

    def selected(event):
        if Clicked.get() == "Blue 50-1,000 µl":
            Volume1 = Label(root, text="0.1000")
            Volume2 = Label(root, text="0.5000")
            Volume3 = Label(root, text="1.0000")
            Volume1.place(x=175, y=520)
            Volume2.place(x=525, y=520)
            Volume3.place(x=825, y=520)
        elif Clicked.get() == "Yellow 5-100 µl":
            Volume1 = Label(root, test="0.0100")
            Volume2 = Label(root, text="0.0500")
            Volume3 = Label(root, text="0.1000")
            Volume1.place(x=175, y=520)
            Volume2.place(x=525, y=520)
            Volume3.place(x=825, y=520)
        elif Clicked.get() == "Purple 0.2 – 5 ml":
            Volume1 = Label(root, test="0.5000")
            Volume2 = Label(root, text="2.5000")
            Volume3 = Label(root, text="5.000")
            Volume1.place(x=175, y=520)
            Volume2.place(x=525, y=520)
            Volume3.place(x=825, y=520)
        else:
            Volume1 = Entry(root)
            Volume2 = Entry(root)
            Volume3 = Entry(root)
            Volume1.place(x=175, y=520, width=75)
            Volume2.place(x=525, y=520, width=75)
            Volume3.place(x=825, y=520, width=75)

此功能可用于以下各项:

    #Pipette Options Selection List
    Pipette_Options = [
        "Select",
        "Blue 50-1,000 µl",
        "Yellow 5-100 µl",
        "Purple 0.2 – 5 ml"
     ]
    #Drop-Down for Pipettes
    Clicked = StringVar()
    Clicked.set(Pipette_Options[0])

    Pipette_Drop = OptionMenu(root, Clicked, *Pipette_Options,    command=selected)
    Pipette_Drop.place(x=280, y=445)

Tags: textgetifplaceroot语句widthlabel
3条回答

如果您希望“if”和“else”如您所述一起运行,为什么不将它们合并在一起。我认为你的代码需要更多的描述。你到底想做什么

一旦发现命中,Python就会停止elif-else语句。因此,当if Clicked.get() == "Blue 50-1,000 µl"返回True时,它不会继续计算其余的elif/else语句。 据我从你的代码判断,这应该是经过深思熟虑的

改用字典:

def f1():
    Volume1 = Label(root, text="0.1000")
    Volume2 = Label(root, text="0.5000")
    Volume3 = Label(root, text="1.0000")
    Volume1.place(x=175, y=520)
    Volume2.place(x=525, y=520)
    Volume3.place(x=825, y=520)
    
def f2():
    Volume1 = Label(root, test="0.0100")
    Volume2 = Label(root, text="0.0500")
    Volume3 = Label(root, text="0.1000")
    Volume1.place(x=175, y=520)
    Volume2.place(x=525, y=520)
    Volume3.place(x=825, y=520)
def f3():
    Volume1 = Label(root, test="0.0100")
    Volume2 = Label(root, text="0.0500")
    Volume3 = Label(root, text="0.1000")
    Volume1.place(x=175, y=520)
    Volume2.place(x=525, y=520)
    Volume3.place(x=825, y=520)
    
d = {"Blue 50-1,000 µl": f1, 
     "Yellow 5-100 µl": f2,
     "Purple 0.2 – 5 ml": f3}
if d.has_key(Clicked.get()):
     d[Clicked.get()]()
else: 
    print("another action...")

相关问题 更多 >