通过单击按钮验证Python Tkinter名称输入吗?

时间:2020-08-26 23:25:18

标签: python validation tkinter

因此,这里有一个程序,该程序首先显示一条信息消息,然后单击下一步,它告诉您在打开主窗口之前输入您的姓名。

信息->(下一个)输入名称->(下一个)

当我在输入框中输入我的名字时,我希望检查它是否包含1.numbers和2.not空白。在validate =“ key”选项下,这意味着一旦我开始输入,它就会生效。但是,我希望它仅在按下NEXT按钮后才检查名称。如果没有,它将打开errorbox()

class errorbox():
    def __init__(self):
        windowError = Tk()
        windowError.title("Error")
        windowError.geometry('300x400')
        error_message = Label(windowError, font=("Bold", 10), justify="left", text="Please enter a valid name")
        
def clicked1():
    description.configure(text="Please enter your name")
    nameBox = Entry(windowSplash, width=20, textvariable=name)
    nameBox.place(rely=0.5, x=130, anchor=W)
    reg = windowSplash.register(validate)
    nameBox.config(validate="none",validatecommand=clicked2)
    button2 = Button(text="Next", bg="white", width=5, command=lambda:[clicked2(),validate()])
    button2.place(rely=0.5, x=300, anchor=E)
    button1.destroy()

def validate(input):
    if input.isdigit():
        print("Invalid name was entered" + input)
        errorbox()
        return False
    elif input is "":
        print("No name entered")
        errorbox()
        return False
    else:
        
        return True

def clicked2():
    print(name.get(), "logged in...")
    windowSplash.destroy()
    windowTool = Tk()
    windowTool.title("Radial Measurements Calculator Tool")
    windowTool.geometry('300x400')

name = StringVar()

windowSplash.mainloop()

1 个答案:

答案 0 :(得分:0)

欢迎使用Stack Overflow社区。

我可能已经解释了您的问题,但是请确保下次您询问时提供minimal, reproducible example

这是我观察到的几件事。

  1. validate函数将input作为参数,因此请确保将lambda input = name.get(): [clicked2(),validate(input)]传递给lambda函数。
  2. 通过检查input.isdigit()不能保证在字符之后/之间可能没有数字,因此建议您遍历字符串并检查isdigit() / type()或使用{ {1}}模块。此外,检查空字符串的有效方法可能是re
  3. 如果您打算仅在验证后打开新窗口,建议您在某种情况下从if not name.get():函数调用clicked2,而不要使用validate按钮,因为在在这种情况下,您的退货表格next不会被使用。