In this Python Tkinter tutorial, we will learn about validations and how to implement validation in Python Tkinter. Also, we will cover these topics.

  • Python Tkinter Validation
  • Python Tkinter Validate Entry
  • Python Tkinter Password Validation
  • Python Tkinter Entry Validate Integer
  • Python Tkinter Entry Validate Example
  • Python Tkinter Entry Validate focusout
  • Python Tkinter Spinbox Validate

Python Tkinter Validation

Validation in Python Tkinter means declaring user inputs officially acceptable. In other words, checking if the information shared by the user matches the company standards.

  • There are mainly three types of Validations:
    1. Type Check: check the data type
    2. Length Chcek: check max or min length
    3. Range Check: from-to
  • Validation can be performed using Excepting handlers and by raising flag.
  • Exception handlers are try, except, finally
  • Flag raising include booleans and while loop.
  • In this tutorial, we have explained validation in Python Tkinter with real life examples and projects.

Read Python Tkinter On-Off Switch

Python Tkinter Validate Entry

In this section, we will learn how to add validation on the Entry widget in Python Tkinter.

  • Entry widget in Python Tkinter is exposed to all kind of user inputs and used for wide variety of functionalities. Like it acts as a String input, numerical input and password input.
  • All these inputs contain varieties of validations like field can’t be empty, minimum or maximum number of characters, etc.
  • We have covered password validation in other section, so in this section we will cover
    • empty string validation : some data must be provided by user.
    • minimum and maximum character validation : min and max characters in a string.
    • Only string validation : User input must be string only eg. name can’t have number.

Source Code with explanation:

In this example, we have created a simple GUI using Python Tkinter. Firstly, we have created a simple interface to accept the user input and then when the user clicks on the submit button function named validation() is called.

def validation(): name = name_tf.get() msg = '' if len(name) == 0: msg = 'name can\'t be empty' else: try: if any(ch.isdigit() for ch in name): msg = 'Name can\'t have numbers' elif len(name) <= 2: msg = 'name is too short.' elif len(name) > 100: msg = 'name is too long.' else: msg = 'Success!' except Exception as ep: messagebox.showerror('error', ep) messagebox.showinfo('message', msg)

  • In this code, on line 2 we have fetched the value from the entry box and saved it in a variable ‘name’.
  • msg = ' ', msg has empty string this will be used to store the messages of condtions and it will be displayed in the end.
  • If condition is started and lenght of name is checked. If the length is 0 that means there is no input in the entry box. In that case user will see a message ‘name can’t be empty’ .
  • In the else section, using exception handler try and Except if-else condition is used to check multiple parameters.
    • any(ch.isdigit() for ch in name): This line of code checks for any number in the name. If found then error message will be displayed.
    • len(name) <= 2:If the total characters in the name is less than 3 than error message will be displayed.
    • len(name) > 100: name cannot be greater than 100 characters.
  • messagebox.showinfo('message', msg)This code displays the message in a pop up. Here ‘message’ is the title of message box promt and msg contains the message.

from tkinter import * from tkinter import messagebox ws = Tk() ws.title('Pythonguides') ws.geometry('400x300') ws.config(bg='#04B2D9') def validation(): name = name_tf.get() msg = '' if len(name) == 0: msg = 'name can\'t be empty' else: try: if any(ch.isdigit() for ch in name): msg = 'Name can\'t have numbers' elif len(name) <= 2: msg = 'name is too short.' elif len(name) > 100: msg = 'name is too long.' else: msg = 'Success!' except Exception as ep: messagebox.showerror('error', ep) messagebox.showinfo('message', msg) frame = Frame( ws, padx=10, pady=10 ) frame.pack(pady=20) Label( frame, text='Enter Name' ).grid(row=0, column=1) name_tf = Entry( frame, font = ('sans-sherif', 14) ) name_tf.grid(row=0, column=1) Button( frame, text='Submit', pady=10, padx=20, command=validation ).grid(row=1, columnspan=2) ws.mainloop()

Output:

In this output, there is an entry widget wherein the user can provide any name. On clicking the submit button program will validate on following parameters:

  • The Entry widget is not empty
  • The name is greater than 3 characters and lesst than 100 characters
  • The name is not containing any numerical value.

If all the parameters are ok then the user will see a success message.

Read Python Tkinter notebook Widget

Python Tkinter Password Validation

In this section, we will cover Python Tkinter Password Validation. We will implement all the standard validations on Passwords using Python Tkinter.

  • Using Python Tkinter Entry widget we can create a password field simply by adding optionshow='*'in Python tkinter.
  • Here is the standard list of Password validations:
    • atleast 1 uppercase
    • atleast 1 lowercase
    • atleast 1 special character
    • atleast 1 number
    • minimum 8 charcters
    • Password field can’t be empty
  • In our example we are going to implement all of these using Python Tkinter.

Source Code with explanation:

In this code, we have created GUI using Python Tkinter that accepts Password as user input, and when the user clicks on the submit button the password is validated and if it is as per the defined standard then a ‘success’ pop-up is displayed.

  • We have created a function with the name validation() which is triggered everytime user clicks on the submit button.
  • any() is a python function that works like a OR. Which means it will return True if any of the condition is true.

Here is the explanation of validation() function.

def validation(): password = pwd.get() msg = "" if len(password) == 0: msg = 'Password can\'t be empty' else: try: if not any(ch in special_ch for ch in password): msg = 'Atleast 1 special character required!' elif not any(ch.isupper() for ch in password): msg = 'Atleast 1 uppercase character required!' elif not any(ch.islower() for ch in password): msg = 'Atleast 1 lowercase character required!' elif not any(ch.isdigit() for ch in password): msg = 'Atleast 1 number required!' elif len(password) < 8: msg = 'Password must be minimum of 8 characters!' else: msg = 'Success!' except Exception as ep: messagebox.showerror('error', ep) messagebox.showinfo('message', msg)

  • password = pwd.get()In this line, we have fetched the user input and store it in a variable ‘password’.
  • msg is an empty string that will store the message later in program. All the messages displayed on the pop-up box comes from here.
  • we have created a list of all the special characters on the keyboard.
  • Using if-else statement length of password is checked. If the length is 0 that means Entry box is empty in that case user will see an error message.
  • If the user has provided some input then the else part will be executed where in we have used exception handler try and Except.
  • Inside the try block, using if-else statement password is passed through various parameters. If the password passes all the parameters then ‘success’ message is displayed.
  • The parameters are as following:
    • if not any(ch in special_ch for ch in password)
    • elif not any(ch.isupper() for ch in password)
    • elif not any(ch.islower() for ch in password)
    • elif not any(ch.isdigit() for ch in password)
    • elif len(password) < 8
  • These parameters assures that the password is comprising for atleast 1 uppercase & lowercase character, 1 number and 1 special character. Also, it assures that password field is not empty and at is minimum 8 characters.

from tkinter import * from tkinter import messagebox special_ch = ['~', '`', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '+', '=', '{', '}', '[', ']', '|', '\\', '/', ':', ';', '"', "'", '<', '>', ',', '.', '?'] def validation(): password = pwd.get() msg = ""Turn off validation. if len(password) == 0: msg = 'Password can\'t be empty' else: try: if not any(ch in special_ch for ch in password): msg = 'Atleast 1 special character required!' elif not any(ch.isupper() for ch in password): msg = 'Atleast 1 uppercase character required!' elif not any(ch.islower() for ch in password): msg = 'Atleast 1 lowercase character required!' elif not any(ch.isdigit() for ch in password): msg = 'Atleast 1 number required!' elif len(password) < 8: msg = 'Password must be minimum of 8 characters!' else: msg = 'Success!' except Exception as ep: messagebox.showerror('error', ep) messagebox.showinfo('message', msg) ws = Tk() ws.title('PythonGuides') ws.geometry('500x200') ws.config(bg='#DDF2AE') frame = Frame( ws, bg='#8C8C8B', padx=10, pady=10 ) frame.pack(pady=30) Label( frame, bg='#8C8C8B', text='Password', font = ('sans-serif', 14) ).grid(row=0, column=0, padx=(0, 10)) pwd = Entry( frame, font = ('sans-serif', 14), show= '*' ) pwd.grid(row=0, column=1) submit = Button( frame, text='Submit', width=20, font = ('sans-serif', 12), command= validation , pady=10 ) submit.grid(row=1, columnspan=2, pady=20) ws.mainloop()

Output:

In this output, we have created a password field using the Python Tkinter Entry widget. The password field has all the validations. Every time user is providing input and clicking on the submit button validation checkup is performed. If everything is as

Read Python Tkinter Checkbutton – How to use

Python Tkinter Entry Validate Integer

In this section, we will cover Python Tkinter Entry Validate Integer. We will learn to check validations for numbers

  • Python Tkinter Entry Validate Integer can be seen in Age and phone number inputs. As these can’t be negative or in decimals.
  • In this, we iterate over each charater of the user input and assure that user has provided numbers only.
  • Incase the user input contains any string, special character or decimal at that time exception will be generated and user will be notified for the same.

Source code:

In this example, we have created a GUI-based application using Python Tkinter wherein the user is asked for his/her age.

  • Once the user clicks on the submit button the function validation() function is triggered.
  • The function validates based upon the following parameters:
    • Age Entry box is not empty
    • Age should’t be negative
    • Age must be an integer
  • If all of these parameters are true than the user recieves ‘success’ message.
  • Here is the explanation of validation() function.

def validation(): msg = '' age = age_tf.get() if len(age)==0: msg='Field can\'t be empty' else: try: if int(age) < 0: msg='Age can\'t be negative' else: msg='Success' except: msg='Age cannot be a string' messagebox.showinfo('info', msg)

  • msg is the epty string that is created to store the message later in program. Message stored in the msg variable will be displayed everytime user clicks on the submit button.
  • age = age_tf.get()in this line, user input is fetched and stored in the variable ‘age’.
  • Using if-else statement length of age is checked. if the length is zero that means the user has not provided any input. In that case, user will recieve error message.
  • In the else section, using exception handler try and except we have make sure that out program didn’t break.
  • Inside the try block if-else statement is used to check if the age is less than 0. Technically, age cannot be negative so user will recieve error message.
  • For the corrrect input user will see ‘success’ pop-up.

from tkinter import * from tkinter import messagebox def validation(): msg = '' age = age_tf.get() if len(age)==0: msg='Field can\'t be empty' else: try: if int(age) < 0: msg='Age can\'t be negative' else: msg='Success' except: msg='Age cannot be a string' messagebox.showinfo('info', msg) ws = Tk() ws.title('PythonGuides') ws.geometry('400x300') ws.config(bg='#0B2D59') frame = Frame( ws, bg='#05DBF2', padx=10, pady=10 ) frame.pack(pady=20) Label( frame, text='Enter Age', bg='#05DBF2', padx=10, pady=10 ).grid(row=0, column=0) age_tf = Entry( frame, font = ('sans-serif', 14) ) age_tf.grid(row=0, column=1) Button( frame, text='Submit', command=validation ).grid(row=1, columnspan=2) ws.mainloop()

The output of integer validation using Python Tkinter

In this output, simple age validating application is created. In this application, user can fill their age and click on submit. In case the user clicks on submit button with no input or incorrect input then he/she will receive a prompt message accordingly.

Read Python Tkinter Radiobutton – How to use

Python Tkinter Entry Validate Example

In this section, we will see a full-fledged application with all the validations using Python Tkinter.

  • In this project we have implemented everything that we have explained so far in this tutorial.
  • We have created a facebook registration form and in that form we have added validations on the Entry widgets.
  • The validations are on the basis of following parameters:
    • Fields cannot be empty
    • first name and last name must be above 3 characters, and can contain only strings.
    • mobile or email field accepts either mobile number or email address.
    • Mobile number must be Integer of 10 digits only
    • email must include @ and dot(.) special characters.

Source code:

from tkinter import * from tkinter import ttk from tkinter import messagebox def mob_email_validation(): special_ch = ['@', '.'] msg = '' me = mob_email.get() if me == '': msg = 'provide Mobile num or Email' else: try: if any(ch.isdigit() for ch in me): if len(me) == 10: mob = int(me) msg = 'success' else: msg = 'incorrect mobile number!' else: if not any(ch in special_ch for ch in me): msg = 'incorrect email!' else: msg = 'success!' except Exception as ep: msg = ep messagebox.showinfo('message', msg) def validation(name_str, elm): msg = '' if name_str == '': msg = f'{elm} is required!' else: try: if len(name_str) <= 2: msg = 'Name is too small' elif any(ch.isdigit() for ch in name_str): msg = 'Name cannot have numbers' else: msg=f'success for {elm}' except Exception as ep: messagebox.showerror('message', ep) messagebox.showinfo('message', msg) def btn_clicked(): validation(fname.get(), 'first name') validation(surname.get(), 'last name') mob_email_validation() def on_click_fname(event): fname.configure(state=NORMAL) fname.delete(0, END) fname.unbind('<Button-1>', on_click_id1) def on_click_surname(event): surname.configure(state=NORMAL) surname.delete(0, END) surname.unbind('<Button-1>', on_click_id2) def on_click_mob_email(event): mob_email.configure(state=NORMAL) mob_email.delete(0, END) mob_email.unbind('<Button-1>', on_click_id3) def disp_date(choice): choice = day_var.get() print(choice) def disp_month(choice): choice = month_var.get() print(choice) def disp_year(choice): choice = year_var.get() print(choice) ws = Tk() ws.title('PythonGuides') ws.geometry('600x600') ws.config(bg='#fff') firstname = StringVar() username = StringVar() password = StringVar() day = [x for x in range(1, 32)] month = [x for x in range(1, 13)] year = [x for x in range(1905, 2022)] # print(date) # print(month) # print(year) Label( ws, text='Sign Up', font = ('sans-serif', 32), bg='#fff' ).grid(row=0, columnspan=2, sticky='EW') Label( ws, text='It\'s quick and easy', font = ('sans-serif', 15), fg = '#606770', bg='#fff', ).grid(row=1, columnspan=2, sticky='EW') Label( ws, text='_'*85, fg='#ccd065', bg='#fff', ).grid(row=2, columnspan=2, pady=(0, 20)) fname = Entry( ws, bg='#fff', font=('sans-serif', 15) ) fname.grid(row=3, column=0, pady=(0, 10)) surname = Entry( ws, bg='#fff', font=('sans-serif', 15), ) surname.grid(row=3, column=1, pady=(0, 10)) mob_email = Entry( ws, bg='#fff', font=('sans-serif', 15), width=43 ) mob_email.grid(row=4, columnspan=2, pady=(0, 10)) # adding placeholders fname.insert(0, 'First name') fname.configure(state=DISABLED) surname.insert(0, 'Surname') surname.configure(state=DISABLED) mob_email.insert(0, 'Mobile number or email address') mob_email.configure(state=DISABLED) # binding placeholders fname.bind('<Button-1>', on_click_fname) surname.bind('<Button-1>', on_click_surname) mob_email.bind('<Button-1>', on_click_mob_email) on_click_id1 = fname.bind('<Button-1>', on_click_fname) on_click_id2 = surname.bind('<Button-1>', on_click_surname) on_click_id3 = mob_email.bind('<Button-1>', on_click_mob_email) dob = LabelFrame( ws, text='Date of birth', font=('sans-serif', 12), bg='#fff', padx=10, pady=10 ) dob.grid(row=5, columnspan=2, sticky='EW', padx=18, pady=(0, 10)) day_var = IntVar() month_var = StringVar() year_var = StringVar() # display defaults day_var.set(day[7]) month_var.set(month[3]) year_var.set(year[-1]) day_cb=ttk.Combobox( dob, textvariable = day_var, font=('sans-serif', 15), width=12, background= ['#fff'] # ToDo ) day_cb.grid(row=6, column=0, padx=(0, 15), ipady=10) month_cb = ttk.Combobox( dob, textvariable=month_var, font=('sans-serif', 15), width=12 ) month_cb.grid(row=6, column=1, padx=(0, 15), ipady=10) year_cb = ttk.Combobox( dob, textvariable=year_var, font=('sans-serif', 15), width=12 ) year_cb.grid(row=6, column=2, ipady=10) day_cb['values'] = day month_cb['values'] = month year_cb['values'] = year # disable editing day_cb['state'] = 'readonly' month_cb['state'] = 'readonly' year_cb['state'] = 'readonly' gender = Frame( ws, bg='#fff', ) gender.grid(row=7, columnspan=2) gen_var = IntVar() gen_var.set(1) female_rb = Radiobutton( gender, text='Female', bg='#fff', variable=gen_var, value=1, font = ('sans-serif', 15), anchor='w' ) female_rb.pack(fill=BOTH, expand=True, side=LEFT, padx=10, pady=10, ipadx=10, ipady=10) male_rb = Radiobutton( gender, text='Male', bg='#fff', variable=gen_var, value=2, font = ('sans-serif', 15), anchor='w' ) male_rb.pack(fill=BOTH, expand=True, side=LEFT, padx=10, pady=10, ipadx=25, ipady=10) custom_rb = Radiobutton( gender, text='Others', bg='#fff', variable=gen_var, value=3, font = ('sans-serif', 15), anchor='w' ) custom_rb.pack(expand=True, fill=BOTH, side=LEFT, padx=10, pady=10, ipadx=10, ipady=10) terms =''' By clicking Sign Up, you agree to our Terms, Data Policy and Cookie Policy. You may receive SMS notifications from us and can opt out at any time. ''' Label( ws, text=terms, wraplength=500, bg='#fff' ).grid(row=8, columnspan=2) signup_btn = Button( ws, text='Sign Up', command= btn_clicked, #ToDo font = ('sans-serif', 18), padx=40, pady=10, ) signup_btn.grid(row=9, columnspan=2) ws.mainloop()

Output:

In this example, the Signup form is displayed. This sign-up form is created using Python Tkinter and it has Validation applied on Entry widgets.

Read How to make a calculator in Python

Python Tkinter Entry Validate focusout

In this section, we will cover Python Tkinter Entry Validation focus out. Every time the user will move to other widgets the previous widget will validate if the user input is up to the standard.

  • Focus out means as soon as user leaves the widget an even is activated.
  • In this case the event will validate if the user input is valid or not. The program will through error message immediately if user input didn’t meet the criteria.
  • In our case, we will do something different. We will ask for user input and will display it immedietly after the user switches to other widget.
  • validate is the option in the widget that provides multiple options like
Validate whenever the
‘focusin’ Validate whenever the widget gets focus.
‘focusout’ Validate whenever the widget loses focus.
‘key’ Validate whenever any keystroke changes the widget’s contents.
‘all’ Validate in all the above situations.
‘none’ This is the default option value it Turns off validation. Please Note th that this is the string ‘none’, not the special Python value None.

Source Code

In this example, callback function returns that value entered by user immediately after the Python Tkinter Entry widget looses focus.

  • validate is the option in Python Tkinter Entry widget that is set to ‘focusout’.
  • validatecommand is the function that will be called everytime the widget looses focus.

from tkinter import * ws = Tk() ws.title('PythonGuides') ws.geometry('400x200') ws.config(bg='#F2BD1D') name_var = StringVar() age_var = IntVar() age_var.set(18) def callback(): disp.config(text=f'Your favorite city is {name_var.get().capitalize()}') return True frame = Frame( ws, padx=10, pady=10, bg='#F2BD1D' ) frame.pack(pady=20) Label( frame, text='City Name', font=('sans-serif', 14), bg='#F2BD1D' ).grid(row=0, column=0) Entry( frame, textvariable=name_var, validate='focusout', validatecommand=callback, font=('sans-serif', 14) ).grid(row=0, column=1, padx=10) # this entry widget is used to change the focus Entry( frame, width=2 ).grid(row=1, columnspan=2, padx=10) disp = Label( frame, text='tap tab', font=('sans-serif', 14), relief=SOLID, padx=10, pady=10 ) disp.grid(row=2, columnspan=2, pady=20) ws.mainloop()

Output:

In this output, cityname is asked. User fills the city name and clicks on the tab key on the keyboard to navigate to the other widget. As soon as widget looses focus, callback validate function is called and name of the city is displayed.

Read Python Tkinter Menu bar – How to Use

Python Tkinter Spinbox Validate

Python Tkinter Spinbox is a type of Entry widget with the feature of spinning across the data.

  • Python Tkinter Spinbox allows developer to feed in some data that user can select simply by clicking on the upward or downward arrow.
  • It also allows to take user input in the real time.
  • Validation on spinbox is applied on the user input. Let’s suppose users are allowed to add more numbers in the Python Tkinter Spinbox. At that time entry of string will break the program. so to avoid that situation validations are applied on the Python Tkinter Spinbox.
  • In our example, we will see the demonstration of Python Tkinter Spinbox Validate.

Source Code:

  • In this code, we have created Python Tkinter Spinbox and applied validations on it.
  • Validations are based upon following parameters:
    • Python Tkinter Spinbox can’t be empty
    • Python Tkinter Spinbox accepts only Integer
  • Everytime user fills the information and clicks on the display button, validation() function is triggered. Here is the explanation of Validation function.

def validation(): spin = sb.get() if len(spin) == 0: msg.config(fg='red', text='Input can\'t remain empty') else: if not spin.isdigit(): msg.config(fg='red', text='Input must be an integer') else: msg.config(fg='#fff', text=spin, font=('sans-serif', 14))

  • spin variable holds the current value on the Python Tkinter Spinbox widget. Let’s say 2 is selected by the user then value in variable spin will be 2.
  • if len(spin) == 0: this line checks if the Python Tkinter Spinbox is empty. In other words, if user will not provide any input then this condition will become true and an error message will be displayed.
  • In the else section, if not spin.isdigit():validates if entered value is not integer. If that is so then error message is displayed other wise the entered number is displayed.

from tkinter import * def validation(): spin = sb.get() if len(spin) == 0: msg.config(fg='red', text='Input can\'t remain empty') else: if not spin.isdigit(): msg.config(fg='red', text='Input must be an integer') else: msg.config(fg='#fff', text=spin, font=('sans-serif', 14)) ws = Tk() ws.title('PythonGuides') ws.geometry('300x300') ws.config(bg='#1E3C40') data = [1,2,3,4,5,6,7,8] sb =Spinbox( ws, values=data, font=('sans-serif', 14) ) sb.pack(pady=25) Button( ws, text='Display', padx=20, pady=5, command=validation ).pack(pady=10) msg = Label( ws, text='', bg='#1E3C40' ) msg.pack(pady=10) ws.mainloop()

Output:

  • In this output, Series of numbers are displayed using Python Tkinter Spinbox.
  • Users can click on the upward or downward arrow to move the numbers.
  • Clicking on the display button will display the selected number in Python Tkinter Spinbox.
  • Users can provide their inputs too in the Python Tkinter spinbox but it must be an Integer value only.
  • An error message will be displayed if anything other than an integer is provided.
  • An error will also generate if user clicks on display button with empty spinbox.

You may also like the following Python Tkinter examples:

  • Python Tkinter messagebox
  • Python Tkinter Events
  • Python Tkinter Spinbox
  • How to read a text file using Python Tkinter
  • Python Tkinter Frame
  • Python Tkinter Animation
  • Python Tkinter search box

In this tutorial, we have learned Python Tkinter Validation. Also, we have covered these topics.

  • Python Tkinter Validation
  • Python Tkinter Validate Entry
  • Python Tkinter Password Validation
  • Python Tkinter Entry Validate Integer
  • Python Tkinter Entry Validate Example
  • Python Tkinter Entry Validate focusout
  • Python Tkinter Spinbox Validate

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

You are watching: Python Tkinter Validation examples. Info created by GBee English Center selection and synthesis along with other related topics.