使用 Python,我该如何尝试 - 除了单个函数中的几个不同输入,如果其中一个失败,其余部分仍会得到处理?
Using Python, how can I try - except a few different inputs in a single function, where if one fails, the remainder still get processed?
我在 Python 仍然是一个新手,如果这是一个新手问题,我很抱歉。我的程序中有这段代码:
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)
为简单起见,我以我希望用户输入的格式添加了变量 entryBox1 和 entryBox2。
基本上,我想在 2 个或更多 tkinter 输入框中接收输入,当按下一个按钮时,它会查看所有输入框中的输入,并且只将这些输入分配给它们的关联值(如果它们是整数) .如果一个或多个不是整数,它只是跳过该输入并继续。一旦查看了所有输入,无论是否有效,它都会使输入框空白(使用 entryBox1.delete(0,99))
目前,如果我要使用上面的变量,字符串 "not a number" 将阻止对任何其他变量进行有效性测试。
根据我之前的阅读,我想我可以通过将 try/except args 放在 for 循环中来获得我想要的结果,但我不确定如何去做。如有任何建议,我们将不胜感激。
只需使用 for
循环,不要在 except 块中使用 return
。
编辑: 正如@TaraMatsyc 指出的那样,也将 currentValuePumpOn/Off
添加到循环中。
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)
我在 Python 仍然是一个新手,如果这是一个新手问题,我很抱歉。我的程序中有这段代码:
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)
为简单起见,我以我希望用户输入的格式添加了变量 entryBox1 和 entryBox2。
基本上,我想在 2 个或更多 tkinter 输入框中接收输入,当按下一个按钮时,它会查看所有输入框中的输入,并且只将这些输入分配给它们的关联值(如果它们是整数) .如果一个或多个不是整数,它只是跳过该输入并继续。一旦查看了所有输入,无论是否有效,它都会使输入框空白(使用 entryBox1.delete(0,99))
目前,如果我要使用上面的变量,字符串 "not a number" 将阻止对任何其他变量进行有效性测试。
根据我之前的阅读,我想我可以通过将 try/except args 放在 for 循环中来获得我想要的结果,但我不确定如何去做。如有任何建议,我们将不胜感激。
只需使用 for
循环,不要在 except 块中使用 return
。
编辑: 正如@TaraMatsyc 指出的那样,也将 currentValuePumpOn/Off
添加到循环中。
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)