Search code examples
pythonpython-3.xtkintertkinter-canvastkinter-entry

verifying data inside tkinter entry box. if its numeric or alpha or an email


from tkinter import *
import os
te=Tk()
te.geometry('300x200')
L1 = Label(text = "User Name").grid(row=1,column=0)
E1 = Entry( te)
E1.grid(row=1,column=2)
L2 = Label(text="full Name").grid(row=2,column=0)
E2 = Entry( te)
E2.grid(row=2,column=2)
L3 = Label(text="email").grid(row=3,column=0)
E3 = Entry( te)
E3.grid(row=3,column=2)
L4 = Label(text="admission no.").grid(row=4,column=0)
E4 = Entry(te)
E4.grid(row=4,column=2)
def adduser():
    add=open(E1.get(),"a+")
    add.write(E2.get()+":")
    add.write(E3.get()+":")
    add.write(E4.get()+":")
    add.write(E1.get())
    add.close()
    B5.config(state="disabled")
    print('registraion susscefull')
    B6=Button(text="  login  ",command=main)
    B6.grid(row=5,column=1)
def main():
    os.system("main.py")
B5=Button(text="register",command=adduser)
B5.grid(row=5,column=1)
te.mainloop()

Hello coders, I need some help with validations in tkinter so this is what I need:

  1. no space should be in username and at least use of 1 number
  2. email id should be checked that @ and .com are used
  3. admission number should be only integers
  4. full name should be only alphabets

I tried but did not have any success and now you guys are my last hope for this. Please help. I'm still learning and looking forward for your help and code.

Thanks and have a great day.


Solution

  • Take a look at this example:

    from tkinter import *
    from tkinter import messagebox
    
    root = Tk()
    
    def check(): #function to check 
        if '@' not in e2.get() or '.com' not in e2.get(): #if @ or .com is present
            messagebox.showinfo('Not a valid email address','Enter a valid email address')
        else: #if not show error message
            messagebox.showinfo('Success','Succesfull!')
    
    e2 = Entry(root)
    e2.pack(padx=10,pady=10)
    
    b = Button(root,text='Check mail',command=check)
    b.pack(padx=10,pady=10)
    
    root.mainloop()
    

    In this example a simple check is provided to check if it has '@' or '.com' in it.

    And, since you asked a way to only allow alphabets, take a look at this simple validation.

    from tkinter import *
    from tkinter import messagebox
    
    root = Tk()
    
    def validate(inp):
        if inp == "": #to begin typing
            return True
        elif inp.isalpha(): #to only allow alphabets
            return True
        elif ' ' in inp: #to allow space in between
            return True
        else:
            return False #dont allow anything else
    
    vcmd = root.register(validate) #register the function
    
    e = Entry(root,validate='all',validatecommand=(vcmd,'%S')) #now add validating to it
    e.pack(padx=10,pady=10)
    
    root.mainloop()
    

    To understand more better about validation, take a look at Bryan Oakleys answer here