我正在编写一个程序,它可以获取用户的个人信息,如姓名年龄国家等。
myfont = f.Font(family='Maiandra GD')
agel = Label(root, text="Age :", font=myfont, bg="#C5B358", bd=4, relief="raised").place(relx=0.4, rely=0.62, relwidth=0.08, anchor='n')
ageE = Entry(root, font=myfont, bd=2, relief="sunken").place(relx=0.54, rely=0.62, width=265, anchor='n')
button = Button(root, text="START", font=myfont, borderwidth=10, bg="#C5B358", command=start).place(relx=0.5, rely=0.735, relwidth=0.235, anchor='n')
但我想让程序弹出一个错误信息框,要求只输入整数,而不是接受一个字符串的年龄。
这是我目前尝试过的,但没有效果。
def start():
print("START")
def popup():
messagebox.showerror("Invalid input !!", "Insert only integers in age entry!")
v = StringVar()
agel = Label(root, text="Age :", font=myfont, bg="#C5B358", bd=4, relief="raised").place(relx=0.4, rely=0.62, relwidth=0.08, anchor='n')
ageE = Entry(root, font=myfont, bd=2, relief="sunken", textvariable=v).place(relx=0.54, rely=0.62, width=265, anchor='n')
s=v.get()
if s.isnumeric():
button = Button(root, text="START", font=myfont, borderwidth=10, bg="#C5B358", command=start).place(relx=0.5, rely=0.735, relwidth=0.235, anchor='n')
else:
button = Button(root, text="START", font=myfont, borderwidth=10, bg="#C5B358", command=popup).place(relx=0.5, rely=0.735, relwidth=0.235, anchor='n')
如果你试图转换一个不能转换为整数的字符串,解释器会抛出一个值错误。
try:
input_age = int(ageE.get())
except ValueError:
messagebox.showerror('"Invalid input !!", "Insert only integers in age entry!"')