我创建了一个简单的程序,它询问用户的姓名和年龄。然后,程序将从文本框中获取详细信息,并算出 5 年后他们的年龄。
界面很好。这是我遇到困难的验证。当用户输入字母而不是数字时,程序会显示一条错误消息,但无论如何都会继续运行。我尝试过使用 while True:
循环,但这似乎只会使程序崩溃。
这是我已经写过的内容:
def calculate():
name = (textboxName.get())
age = (textboxAge.get())
if age.isalpha():
tkinter.messagebox.showinfo("Error", "The Age is invalid")
textboxAge.delete("0","end")
newAge = int(age)+5
print("Hello",name)
print("In 5 years time you will be",newAge)
我看过其他一些教程,但它们有点令人困惑。我将通过添加另一个 elif
和以下代码来扩展它
elif age >= 100:
tkinter.messagebox.showinfo("Error", "You have entered a number greater than 100")
textboxAge.delete("0","end")
但这不喜欢它是字符串而不是整数。
- 检查文本框中是否输入了数字的最佳方法是什么?
最佳答案
def calculate():
name = (textboxName.get())
age = (textboxAge.get())
try:
newAge = int(age)+5
except ValueError:
tkinter.messagebox.showinfo("Error", "The Intended Reading Age is invalid")
textboxAge.delete("0","end")
return
print("Hello",name)
print("In 5 years time you will be ",newAge)
# ...
如果在try
部分的某个地方发生错误,python不会崩溃,而是跳转到 except
部分。关键步骤是将age
转换为整数。如果它是字符串,则会抛出ValueError
。在这种情况下,将显示消息框,并且文本框中的文本将被删除。 return
then 将停止该函数,因此其余部分将不会被处理。如果 try
部分没有任何反应,则将跳过 except
。
关于python - python 中的 Tkinter 文本输入验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47100670/