简体   繁体   中英

Using Python, how can I try - except a few different inputs in a single function, where if one fails, the remainder still get processed?

I am quite a novice at Python still, so I apologize if this is a novice question. I have this piece of code in my program:

entryBox1 = "not a number"
entryBox2 = 27
def setValues():
    content = entryBox1.get()
    if content != "":
            try:
                    int(content)
                    currentValuePumpOn.set(content)
            except ValueError:
                return
    content = entryBox2.get()
    if content != "":
            try:
                    int(content)
                    currentValuePumpOff.set(content)
            except ValueError:
                return
    entryBox1.delete(0, 99)
    entryBox2.delete(0, 99)

For simplicity, I have added the variables entryBox1 and entryBox2 in a format that I might expect the user to put in.

Basically, I want to receive input in 2 or more tkinter entry boxes, and when a button is pushed, it looks at the inputs in all the entry boxes and only assigns those inputs to their associated values if they are integers. If one or more is not an integer, it just skips over that input and carries on. Once all the inputs have been looked at, valid or not, it blanks the entrybox (with entryBox1.delete(0,99))

At the moment, if I were to use the variables above, the string "not a number" would prevent any further variables from being tested for validity.

Based on my prior reading, I think I could get the result I want by putting the try/except args in a for loop, but I'm not certain how to go about that. Any advice would be appreciated.

Just use a for loop and don't return in the except block.

EDIT: As @TaraMatsyc points, add the currentValuePumpOn/Off to the loop also.

def setValues():
    for eBox, currentValuePump in ((entryBox1, currentValuePumpOn), 
                                   (entryBox2, currentValuePumpOff)):
        content = eBox .get()
        if content != "":
                try:
                    int(content)
                    currentValuePump.set(content)
                except ValueError:
                    pass
        eBox.delete(0, 99)

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