[英]Tkinter - Asking the user for integer input until they give a valid response in tkinter entry box
我正在编写一个程序,它获取用户的个人信息,例如姓名年龄 state 等
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')
但不是接受年龄的字符串输入,我希望程序弹出一个错误消息框,要求仅输入 integer
这是我迄今为止尝试过的,但它不起作用
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')
如果您尝试将无法转换的字符串转换为 integer,解释器将抛出值错误。
try:
input_age = int(ageE.get())
except ValueError:
messagebox.showerror('"Invalid input !!", "Insert only integers in age entry!"')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.