我收到此错误" ValueError:基数为10的int()的无效文字:' g'"当我在输入框中输入字母或小数时。输入框只有整数,我想知道是否可以给出一条消息,说明"你必须输入一个数字"当他们尝试输入一封信时,或类似的东西。继承了我的一些代码:
def checkAnswer():
mainAnswer = entry1.get()
if len(mainAnswer) == 0:
messagebox.showwarning(message='-You must enter some numbers first!')
return
if int(mainAnswer) != answer:
messagebox.showwarning(message='Sorry...the correct answer is: ' + str(answer))
else:
messagebox.showinfo(message='Correct!')
答案 0 :(得分:3)
您获得的例外情况是当int(mainAnswer)
不是数字时尝试执行mainAnswer
。解决问题的一种方法是:
try:
int(mainAnswer)
except ValueError:
messagebox.showwarning(message="You must enter a number")
return
# the rest of your code
答案 1 :(得分:0)
try:
int_answer = int(mainAnswer)
except ValueError:
int_answer = None
if int_answer is None:
... # Show the error.
答案 2 :(得分:0)
我只是检查一下类型。此外,如果你使用elif,你不应该需要那个空的回报。您也可能需要反转类型检查和len检查,但我认为这对此答案不重要。
def checkAnswer():
mainAnswer = entry1.get()
if type(mainAnswer) != int:
messagebox.showwarning(message='You must enter a number.')
elif len(mainAnswer) == 0:
messagebox.showwarning(message='-You must enter some numbers first!')
elif int(mainAnswer) != answer:
messagebox.showwarning(message='Sorry...the correct answer is: ' + str(answer))
else:
messagebox.showinfo(message='Correct!')