This complete python tutorial explains, how to create a Registration form using Python Tkinter and a login page in python Tkinter with database sqlite3. Also, I have explained how to validate form fields in the registration form in Python Tkinter. I hope, you will like this, registration form in Python using Tkinter example.
All the data will be stored and fetched using the SQLite3 database. This is a complete project on the registration form in python with database, that can be used to add registration & login screens to any desktop application in Python.
Login and Registration form in Python using Tkinter Overview
- The Login and Registration forms are created using Python library ‘Tkinter.’ [Read more about Python Tkinter]
- Tkinter allows creating GUI-based applications and is rich with helpful widgets.
- For the database, we have used SQLite3 which comes pre-installed with python. It is a lighter version of SQL and can hold 281 terabytes of data.
- We have added validation on all the Entry Fields in the project that means it is mandatory to provide all the information. Not doing so will prompt an error message.
- Exception handlers are used to avoid breaking the program also you will see the error using a message box.
- Names of all the countries in the ‘North America‘ continent are displayed in the dropdown. If you want to add more countries, simply replace countries.txt with your text file but make sure to change the name in the code at line 129. An easier way would be to edit the data of inside countries.txt.
- Here is the description of widgets used in the program. Also, we have a dedicated section for each widget used in the project and we added a link in front of each.
Widget Name | Widget Overview |
---|---|
Python Tkinter Frame | We have used two frames with the name left frame & right frame. they position the logging and registration page. The geometry manager used to position frames is Place. |
Tkinter Label | The Label widget is used to display text on the application screen. All the text on the screen like ‘Enter Email’, ‘Enter Name’, etc are added using the Label widget. |
Entry widgets | Entry boxes provide white space to the user and the user can type the details inside it. It is one of the most important widgets used in any application. |
Python Tkinter Radiobutton | Radiobutton widget is used to provide a single choice to the users. In the application. the user can choose only one gender at a time. |
OptionMenu | OptionMenu is used to display the dropdown. It is used to display the list of countries in the application. Learn more about OptionMenu. |
Button | Buttons are used to perform an action when clicked. In this application, we have used two buttons with the names as Login and Register. |
Read Python QR code generator using pyqrcode in Tkinter
Python Tkinter Registration Form
In this section, we will talk about the registration form in python using tkinter. We will be discussing widgets and the purpose of using them at that point. The code shared here is only for the interface of the registration page. Complete application code is shared at the bottom of the page.
Frame Widget
- ws is the main window on which we are going to place a frame
- bd is the border of the frame
- bg is the background colour.
- relief is to provide a special effect.
- Here geometry method used is ‘pack’ but in the full code below we have used the place as place allows us to position the widget with higher accuracy.
- the thought behind creating this widget is to place other widgets inside it so that everything looks organized.
right_frame = Frame(
ws,
bd=2,
bg='#CCCCCC',
relief=SOLID,
padx=10,
pady=10
)
right_frame.pack()
Label Widget
- The Label is used to add text to the application. We have used Label multiple times to display different text.
- Here I will be explaining it once and that will be applicable on all the labels used in the program.
- in the below code Label is the keyword used to create the label widget.
- We are placing this label on the right_frame.
- any text added here will be displayed on the application
- We are using grid as a geometry method to position the text.
Label(
right_frame,
text="Enter Name",
bg='#CCCCCC',
font=f
).grid(row=0, column=0, sticky=W, pady=10)
Entry Widget
- The Entry widget is used to take input from the user. It provides a blank space where the user can type any text.
- Entry widget is used multiple times in the code this explanation is implemented on all.
- Entry keyword is used to all call entry widget and it is placed on the right_frame
- We are using the grid as a geometry method to position the text.
register_name = Entry(
right_frame,
font=f
)
register_name.grid(row=0, column=1, pady=10, padx=20)
Radiobutton
- The Radiobutton is used to provide multiple options to the user but the user can select only one option.
- We have created another frame with the name ‘gender_frame’ to hold all the radio buttons.
- text is the name we want to show next to Radiobutton like in this case ‘male’.
- bg is the background color of the Radiobutton.
- variable means the value will change so in this case we have set it var which is StringVar(). Now the value provided must be a string. If var is set to IntVar() in that case value should be an integer.
- value could be an integer or string depends upon the type of variable we have used. Value helps in identifying which radio button is selected.
- pack geometry method is used with permission to expand in available space & stick to their left.
- When 3 radio buttons are placed with the same properties then they all look the same and organized.
var = StringVar()
var.set('male')
male_rb = Radiobutton(
gender_frame,
text='Male',
bg='#CCCCCC',
variable=var,
value='male',
font=('Times', 10),
)
male_rb.pack(expand=True, side=LEFT)
OptionMenu
- OptionMenu is used to create a dropdown in the application. It is not ideal to display large data because it does not have a scrollbar but it consumes less space and displays the appropriate amount of options.
- We have used OptionMenu to display a list of countries of the North America Continent.
- under step 1 we have used the keyword OptionMenu to create the widget and we have placed it inside the right_frame, variable assigned is StringVar() which means different string values will be involved. *countries mean all the countries on the list.
- under step 2 we have countries = [] which is an empty list and it will be appended by country names. variable =StringVar() means string will keep on changing.
- under step 3 we are reading the country names from a text file then using a loop we are appending each country inside the list.
country.rstrip('\n')
it removes \n from the list. - grid is the geometry method used to position the widget.
# step 2
countries = []
variable = StringVar()
# step 3
world = open('countries.txt', 'r')
for country in world:
country = country.rstrip('\n')
countries.append(country)
variable.set(countries[22])
# step 1
register_country = OptionMenu(
right_frame,
variable,
*countries)
# step 4
register_country.grid(row=4, column=1, pady=10, padx=20)
Button
- The Button in Python Tkinter is used to trigger activity. Something should happen when it is clicked.
- In this application, the button is used to save the data inside the database.
- Button keyword is used to create a widget and it is placed inside the right_frame.
- width is the right and the left space of the button
- text is the name displayed on the button.
- the cursor is the icon of the mouse pointer. We have used hand2 that means every time user will take the cursor on the button, the cursor will turn into a pointing finger.
- command holds the information about what will happen if the button is clicked. Here we have set it to None which means nothing will happen but in the full code, we have provided a function name to it.
register_btn = Button(
right_frame,
width=15,
text='Register',
font=f,
relief=SOLID,
cursor='hand2',
command=None
)
Registration form using tkinter code
Here is the complete code snippet for the registration form in python using tkinter. This program shares no dependency with the complete code only in terms of User Interface.
from tkinter import *
ws = Tk()
ws.title('PythonGuides')
ws.config(bg='#0B5A81')
f = ('Times', 14)
var = StringVar()
var.set('male')
countries = []
variable = StringVar()
world = open('countries.txt', 'r')
for country in world:
country = country.rstrip('\n')
countries.append(country)
variable.set(countries[22])
right_frame = Frame(
ws,
bd=2,
bg='#CCCCCC',
relief=SOLID,
padx=10,
pady=10
)
Label(
right_frame,
text="Enter Name",
bg='#CCCCCC',
font=f
).grid(row=0, column=0, sticky=W, pady=10)
Label(
right_frame,
text="Enter Email",
bg='#CCCCCC',
font=f
).grid(row=1, column=0, sticky=W, pady=10)
Label(
right_frame,
text="Contact Number",
bg='#CCCCCC',
font=f
).grid(row=2, column=0, sticky=W, pady=10)
Label(
right_frame,
text="Select Gender",
bg='#CCCCCC',
font=f
).grid(row=3, column=0, sticky=W, pady=10)
Label(
right_frame,
text="Select Country",
bg='#CCCCCC',
font=f
).grid(row=4, column=0, sticky=W, pady=10)
Label(
right_frame,
text="Enter Password",
bg='#CCCCCC',
font=f
).grid(row=5, column=0, sticky=W, pady=10)
Label(
right_frame,
text="Re-Enter Password",
bg='#CCCCCC',
font=f
).grid(row=6, column=0, sticky=W, pady=10)
gender_frame = LabelFrame(
right_frame,
bg='#CCCCCC',
padx=10,
pady=10,
)
register_name = Entry(
right_frame,
font=f
)
register_email = Entry(
right_frame,
font=f
)
register_mobile = Entry(
right_frame,
font=f
)
male_rb = Radiobutton(
gender_frame,
text='Male',
bg='#CCCCCC',
variable=var,
value='male',
font=('Times', 10),
)
female_rb = Radiobutton(
gender_frame,
text='Female',
bg='#CCCCCC',
variable=var,
value='female',
font=('Times', 10),
)
others_rb = Radiobutton(
gender_frame,
text='Others',
bg='#CCCCCC',
variable=var,
value='others',
font=('Times', 10)
)
register_country = OptionMenu(
right_frame,
variable,
*countries)
register_country.config(
width=15,
font=('Times', 12)
)
register_pwd = Entry(
right_frame,
font=f,
show='*'
)
pwd_again = Entry(
right_frame,
font=f,
show='*'
)
register_btn = Button(
right_frame,
width=15,
text='Register',
font=f,
relief=SOLID,
cursor='hand2',
command=None
)
register_name.grid(row=0, column=1, pady=10, padx=20)
register_email.grid(row=1, column=1, pady=10, padx=20)
register_mobile.grid(row=2, column=1, pady=10, padx=20)
register_country.grid(row=4, column=1, pady=10, padx=20)
register_pwd.grid(row=5, column=1, pady=10, padx=20)
pwd_again.grid(row=6, column=1, pady=10, padx=20)
register_btn.grid(row=7, column=1, pady=10, padx=20)
right_frame.pack()
gender_frame.grid(row=3, column=1, pady=10, padx=20)
male_rb.pack(expand=True, side=LEFT)
female_rb.pack(expand=True, side=LEFT)
others_rb.pack(expand=True, side=LEFT)
ws.mainloop()
Output:
In this output, you can see that a registration form is created using Python Tkinter. The form has Entry and Selection Fields created using Python Tkinter widgets.
Login page in Python Tkinter with database
This section will see a code explanation for the login page in python tkinter with database. The complete application code is shared at end of the page. The code shown in this section is complete in terms of user interface only.
Frame Widget in Python Tkinter
- Frame widget allows placing other widgets on it. Application look organizes if other widgets are placed on the frame also it gives control over sections.
- Here left_frame is used to create the login section of the application.
- Frame keyword is used to call frame widget and it is placed on the main window i.e ws.
- bd is the border width of the frame widget in Python Tkinter
- relief has different modes by we have used SOLID, it draws the outline. around the frame.
left_frame = Frame(
ws,
bd=2,
bg='#CCCCCC',
relief=SOLID,
padx=10,
pady=10
)
Label Widget in Python Tkinter
- The Label is used to add text to the application.
- in the below code Label is the keyword used to create the label widget.
- We are placing this label on the left_frame.
- any text added here will be displayed on the application
- We are using grid as a geometry method to position the text.
Label(
left_frame,
text="Enter Email",
bg='#CCCCCC',
font=f).grid(row=0, column=0, sticky=W, pady=10)
Entry Widget in Python Tkinter
- The Entry widget is used to take input from the user. It provides a blank space where the user can type any text.
- Entry keyword is used to all call entry widget and it is placed on the left_frame
- We are using the grid as a geometry method to position the text.
email_tf = Entry(
left_frame,
font=f
)
email_tf.grid(row=0, column=1, pady=10, padx=20)
Button Widget in Python Tkinter
- The Button in Python Tkinter is used to trigger activity. Something should happen when it is clicked.
- In this application, the button is used to save the data inside the database.
- Button keyword is used to create a widget and it is placed inside the left_frame.
- width is the right and the left space of the button
- text is the name displayed on the button.
- the cursor is the icon of the mouse pointer. We have used hand2 that means every time user will take the cursor on the button, the cursor will turn into a pointing finger.
- command holds the information about what will happen if the button is clicked. Here we have set it to None which means nothing will happen but in the full code, we have provided a function name to it.
login_btn = Button(
left_frame,
width=15,
text='Login',
font=f,
relief=SOLID,
cursor='hand2',
command=None
)
login_btn.grid(row=2, column=1, pady=10, padx=20)
Complete Code Snippet for Login:
Here is the complete code snippet for the Login form using Python Tkinter. This program shares no dependency with the complete code only in terms of User Interface.
from tkinter import *
ws = Tk()
ws.title('PythonGuides')
ws.config(bg='#0B5A81')
f = ('Times', 14)
left_frame = Frame(
ws,
bd=2,
bg='#CCCCCC',
relief=SOLID,
padx=10,
pady=10
)
Label(
left_frame,
text="Enter Email",
bg='#CCCCCC',
font=f).grid(row=0, column=0, sticky=W, pady=10)
Label(
left_frame,
text="Enter Password",
bg='#CCCCCC',
font=f
).grid(row=1, column=0, pady=10)
email_tf = Entry(
left_frame,
font=f
)
pwd_tf = Entry(
left_frame,
font=f,
show='*'
)
login_btn = Button(
left_frame,
width=15,
text='Login',
font=f,
relief=SOLID,
cursor='hand2',
command=None
)
email_tf.grid(row=0, column=1, pady=10, padx=20)
pwd_tf.grid(row=1, column=1, pady=10, padx=20)
login_btn.grid(row=2, column=1, pady=10, padx=20)
left_frame.pack()
ws.mainloop()
Output:
In this output, you can see that a login form is created using Python Tkinter.
This is how the login page in python tkinter with database looks like.
Registration form using tkinter validation for empty fields
- In this section, we will see the code for identifying the empty fields in the Python Tkinter Registration form, we will see how we can make this mandatory for the user to provide input in the respective text field or selection fields like Radiobutton and OptionMenu.
- We have used a simple strategy to do so. We are checking each Entry field and every time the user has provided input we are incrementing the check_counter variable by 1.
- We have the count of total Entry Fields now we are checking check_count with the total number of fields. If they are equal then the application will proceed and save the data otherwise it will throw an error message for the respective empty field.
- Another validation used in the application is for passwords. Since we two fields for the password in the register form.
- Enter Password
- Renter Password
- We have compared these two with each other. If both are the same then the application will proceed otherwise it will throw the relevant error message.
Code Snippet:
Here is the code used to validate the entry fields in registration form in python.
check_counter=0
warn = ""
if register_name.get() == "":
warn = "Name can't be empty"
else:
check_counter += 1
check_counter=0
if register_email.get() == "":
warn = "Email can't be empty"
else:
check_counter += 1
if register_mobile.get() == "":
warn = "Contact can't be empty"
else:
check_counter += 1
if var.get() == "":
warn = "Select Gender"
else:
check_counter += 1
if variable.get() == "":
warn = "Select Country"
else:
check_counter += 1
if register_pwd.get() == "":
warn = "Password can't be empty"
else:
check_counter += 1
if pwd_again.get() == "":
warn = "Re-enter password can't be empty"
else:
check_counter += 1
Output:
In this output, user is trying to register without providing contact number so he has received an error prompt with the mistake mentioned on it. The same thing will happen if user tries to skip any other field.
Code Snippet:
Here is the code snippet for the password do not match validation.
if register_pwd.get() != pwd_again.get():
warn = "Passwords didn't match!"
else:
check_counter += 1
Output:
Here is the output showing the error prompted when password didn’t matched.
This is how we can implement validation in the registration form using tkinter.
Save Python Tkinter registration form data to sqlite3
As we know, this is an example of a registration form in python using Tkinter with database, in this application, we have used SQLite3 to store data in a database. SQLite3 comes preinstalled with python all you need to is import sqlite3
. to access the data inside the database you can use DB Browser.
Create Database using SQLite in Python Tkinter
This line of code will create a database with the name userdata.db. This file will be stored in the same location where the main file is stored. Using Db Browser you can view and edit the data.
con = sqlite3.connect('userdata.db')
Use the below code you can create table for the database.
con = sqlite3.connect('userdata.db')
cur = con.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS record(
name text,
email text,
contact number,
gender text,
country text,
password text
)
''')
con.commit()
Insert Data using SQLite in Python Tkinter
- Once we have created the database now it is important to connect to the database for inserting data in a database.
cur.execute()
is used to pass the insert query. We have used passed the query in a dictionary format.con.commit()
writes the changes in the database.
con = sqlite3.connect('userdata.db')
cur = con.cursor()
cur.execute("INSERT INTO record VALUES (:name, :email, :contact, :gender, :country, :password)", {
'name': register_name.get(),
'email': register_email.get(),
'contact': register_mobile.get(),
'gender': var.get(),
'country': variable.get(),
'password': register_pwd.get()
})
con.commit()
Here is the output of the record and this is the interface of the Db Browser software.
Full Code Snippet:
Here is the full code of application created using Python Tkinter. We have explained the entire code above section wise.
from tkinter import *
from tkinter import messagebox
import sqlite3
f = ('Times', 14)
con = sqlite3.connect('userdata.db')
cur = con.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS record(
name text,
email text,
contact number,
gender text,
country text,
password text
)
''')
con.commit()
ws = Tk()
ws.title('PythonGuides')
ws.geometry('940x500')
ws.config(bg='#0B5A81')
def insert_record():
check_counter=0
warn = ""
if register_name.get() == "":
warn = "Name can't be empty"
else:
check_counter += 1
if register_email.get() == "":
warn = "Email can't be empty"
else:
check_counter += 1
if register_mobile.get() == "":
warn = "Contact can't be empty"
else:
check_counter += 1
if var.get() == "":
warn = "Select Gender"
else:
check_counter += 1
if variable.get() == "":
warn = "Select Country"
else:
check_counter += 1
if register_pwd.get() == "":
warn = "Password can't be empty"
else:
check_counter += 1
if pwd_again.get() == "":
warn = "Re-enter password can't be empty"
else:
check_counter += 1
if register_pwd.get() != pwd_again.get():
warn = "Passwords didn't match!"
else:
check_counter += 1
if check_counter == 8:
try:
con = sqlite3.connect('userdata.db')
cur = con.cursor()
cur.execute("INSERT INTO record VALUES (:name, :email, :contact, :gender, :country, :password)", {
'name': register_name.get(),
'email': register_email.get(),
'contact': register_mobile.get(),
'gender': var.get(),
'country': variable.get(),
'password': register_pwd.get()
})
con.commit()
messagebox.showinfo('confirmation', 'Record Saved')
except Exception as ep:
messagebox.showerror('', ep)
else:
messagebox.showerror('Error', warn)
def login_response():
try:
con = sqlite3.connect('userdata.db')
c = con.cursor()
for row in c.execute("Select * from record"):
username = row[1]
pwd = row[5]
except Exception as ep:
messagebox.showerror('', ep)
uname = email_tf.get()
upwd = pwd_tf.get()
check_counter=0
if uname == "":
warn = "Username can't be empty"
else:
check_counter += 1
if upwd == "":
warn = "Password can't be empty"
else:
check_counter += 1
if check_counter == 2:
if (uname == username and upwd == pwd):
messagebox.showinfo('Login Status', 'Logged in Successfully!')
else:
messagebox.showerror('Login Status', 'invalid username or password')
else:
messagebox.showerror('', warn)
var = StringVar()
var.set('male')
countries = []
variable = StringVar()
world = open('countries.txt', 'r')
for country in world:
country = country.rstrip('\n')
countries.append(country)
variable.set(countries[22])
# widgets
left_frame = Frame(
ws,
bd=2,
bg='#CCCCCC',
relief=SOLID,
padx=10,
pady=10
)
Label(
left_frame,
text="Enter Email",
bg='#CCCCCC',
font=f).grid(row=0, column=0, sticky=W, pady=10)
Label(
left_frame,
text="Enter Password",
bg='#CCCCCC',
font=f
).grid(row=1, column=0, pady=10)
email_tf = Entry(
left_frame,
font=f
)
pwd_tf = Entry(
left_frame,
font=f,
show='*'
)
login_btn = Button(
left_frame,
width=15,
text='Login',
font=f,
relief=SOLID,
cursor='hand2',
command=login_response
)
right_frame = Frame(
ws,
bd=2,
bg='#CCCCCC',
relief=SOLID,
padx=10,
pady=10
)
Label(
right_frame,
text="Enter Name",
bg='#CCCCCC',
font=f
).grid(row=0, column=0, sticky=W, pady=10)
Label(
right_frame,
text="Enter Email",
bg='#CCCCCC',
font=f
).grid(row=1, column=0, sticky=W, pady=10)
Label(
right_frame,
text="Contact Number",
bg='#CCCCCC',
font=f
).grid(row=2, column=0, sticky=W, pady=10)
Label(
right_frame,
text="Select Gender",
bg='#CCCCCC',
font=f
).grid(row=3, column=0, sticky=W, pady=10)
Label(
right_frame,
text="Select Country",
bg='#CCCCCC',
font=f
).grid(row=4, column=0, sticky=W, pady=10)
Label(
right_frame,
text="Enter Password",
bg='#CCCCCC',
font=f
).grid(row=5, column=0, sticky=W, pady=10)
Label(
right_frame,
text="Re-Enter Password",
bg='#CCCCCC',
font=f
).grid(row=6, column=0, sticky=W, pady=10)
gender_frame = LabelFrame(
right_frame,
bg='#CCCCCC',
padx=10,
pady=10,
)
register_name = Entry(
right_frame,
font=f
)
register_email = Entry(
right_frame,
font=f
)
register_mobile = Entry(
right_frame,
font=f
)
male_rb = Radiobutton(
gender_frame,
text='Male',
bg='#CCCCCC',
variable=var,
value='male',
font=('Times', 10),
)
female_rb = Radiobutton(
gender_frame,
text='Female',
bg='#CCCCCC',
variable=var,
value='female',
font=('Times', 10),
)
others_rb = Radiobutton(
gender_frame,
text='Others',
bg='#CCCCCC',
variable=var,
value='others',
font=('Times', 10)
)
register_country = OptionMenu(
right_frame,
variable,
*countries)
register_country.config(
width=15,
font=('Times', 12)
)
register_pwd = Entry(
right_frame,
font=f,
show='*'
)
pwd_again = Entry(
right_frame,
font=f,
show='*'
)
register_btn = Button(
right_frame,
width=15,
text='Register',
font=f,
relief=SOLID,
cursor='hand2',
command=insert_record
)
# widgets placement
email_tf.grid(row=0, column=1, pady=10, padx=20)
pwd_tf.grid(row=1, column=1, pady=10, padx=20)
login_btn.grid(row=2, column=1, pady=10, padx=20)
left_frame.place(x=50, y=50)
register_name.grid(row=0, column=1, pady=10, padx=20)
register_email.grid(row=1, column=1, pady=10, padx=20)
register_mobile.grid(row=2, column=1, pady=10, padx=20)
register_country.grid(row=4, column=1, pady=10, padx=20)
register_pwd.grid(row=5, column=1, pady=10, padx=20)
pwd_again.grid(row=6, column=1, pady=10, padx=20)
register_btn.grid(row=7, column=1, pady=10, padx=20)
right_frame.place(x=500, y=50)
gender_frame.grid(row=3, column=1, pady=10, padx=20)
male_rb.pack(expand=True, side=LEFT)
female_rb.pack(expand=True, side=LEFT)
others_rb.pack(expand=True, side=LEFT)
# infinite loop
ws.mainloop()
Output:
In this output, you can see the interface of the main application. We have a login screen on the left and a signup screen on the right. It is mandatory to provide all the information in both the login and registration screens.
In this screen, the user trying to log in is not registered that is why she is seeing this error message. The same error will appear if the registered user will put in the wrong credentials.
This is the validation error, user tried to logged in without all fields filled.
This is another validation error, it is important that Password and re-entered passwords are same.
In this output user has provided all the information and password matched with re-enter password column. The user is registered with the application.
In this output, you can see that already registered user can login by providing the correct credentials..
Below you can see, the registration form in python using tkinter data has been saved the sqlite3 database.
You may also like:
- Extract text from PDF Python
- BMI Calculator Using Python Tkinter
- How to Create Countdown Timer using Python Tkinter
- Upload a File in Python Tkinter
- How to Create Date Time Picker using Python Tkinter
I hope you must have been enjoyed the complete login and registration form in python Tkinter example, try the code on your own. It solved the below queries:
- registration form in python with database
- registration form in python using tkinter with database
- registration form in python using tkinter
- python registration form code tkinter
- login page in python tkinter with database sqlite3
- simple login form in python
Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.