微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决通过单击按钮验证Python 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()

解决方法

欢迎使用Stack Overflow社区。​​ p>

我可能已经解释了您的问题,但是请确保下次您询问时提供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不会被使用。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。