Tkinter - 要求用户输入整数,直到他们在 tkinter 输入框中给出有效响应

Tkinter - Asking the user for integer input until they give a valid response in tkinter entry box

我正在编写一个程序来获取用户的个人信息,例如姓名、年龄、状态等

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!"')