Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Simple registration form using Python Tkinter
Tkinter is a Python library for developing GUI (Graphical User Interfaces). It comes as a standard package with Python 3.x, so no additional installation is required. This tutorial shows how to create a registration form using Tkinter widgets.
Creating a Simple GUI Application
Let's start by creating a basic window with a button ?
from tkinter import *
from tkinter import ttk
window = Tk()
window.title("Welcome to TutorialsPoint")
window.geometry('325x250')
window.configure(background="gray")
ttk.Button(window, text="Hello, Tkinter").grid()
window.mainloop()
This code creates a simple window with the following components ?
- Tk() ? Creates the main window
- title() ? Sets the window title
- geometry() ? Sets window size
- configure() ? Sets background color
- mainloop() ? Keeps the window open until closed
Building a Registration Form
Now let's create a proper registration form with labels and entry fields ?
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
def submit_form():
# Get values from entry fields
first_name = first_name_entry.get()
last_name = last_name_entry.get()
email = email_entry.get()
contact = contact_entry.get()
if first_name and last_name and email and contact:
messagebox.showinfo("Success", f"Registration successful for {first_name} {last_name}")
# Clear the form
first_name_entry.delete(0, END)
last_name_entry.delete(0, END)
email_entry.delete(0, END)
contact_entry.delete(0, END)
else:
messagebox.showerror("Error", "Please fill all fields")
# Create main window
window = Tk()
window.title("Registration Form")
window.geometry('400x300')
window.configure(background="lightgray")
# Create and place labels and entry fields
Label(window, text="First Name:", bg="lightgray").grid(row=0, column=0, padx=10, pady=10, sticky="w")
first_name_entry = Entry(window, width=25)
first_name_entry.grid(row=0, column=1, padx=10, pady=10)
Label(window, text="Last Name:", bg="lightgray").grid(row=1, column=0, padx=10, pady=10, sticky="w")
last_name_entry = Entry(window, width=25)
last_name_entry.grid(row=1, column=1, padx=10, pady=10)
Label(window, text="Email ID:", bg="lightgray").grid(row=2, column=0, padx=10, pady=10, sticky="w")
email_entry = Entry(window, width=25)
email_entry.grid(row=2, column=1, padx=10, pady=10)
Label(window, text="Contact Number:", bg="lightgray").grid(row=3, column=0, padx=10, pady=10, sticky="w")
contact_entry = Entry(window, width=25)
contact_entry.grid(row=3, column=1, padx=10, pady=10)
# Submit button
submit_btn = Button(window, text="Submit", command=submit_form, bg="blue", fg="white", width=15)
submit_btn.grid(row=4, column=0, columnspan=2, pady=20)
window.mainloop()
Enhanced Registration Form with Validation
Here's a more advanced registration form with input validation and better styling ?
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import re
class RegistrationForm:
def __init__(self, root):
self.root = root
self.root.title("User Registration Form")
self.root.geometry("500x400")
self.root.configure(bg="#f0f0f0")
# Create main frame
main_frame = Frame(root, bg="#f0f0f0", padx=20, pady=20)
main_frame.pack(expand=True, fill='both')
# Title
title_label = Label(main_frame, text="Registration Form",
font=("Arial", 16, "bold"), bg="#f0f0f0")
title_label.grid(row=0, column=0, columnspan=2, pady=(0, 20))
# Form fields
self.create_form_fields(main_frame)
# Buttons
self.create_buttons(main_frame)
def create_form_fields(self, parent):
fields = [
("First Name:", "first_name"),
("Last Name:", "last_name"),
("Email:", "email"),
("Phone:", "phone"),
("Age:", "age"),
("Gender:", "gender")
]
self.entries = {}
for i, (label_text, field_name) in enumerate(fields):
label = Label(parent, text=label_text, font=("Arial", 10), bg="#f0f0f0")
label.grid(row=i+1, column=0, sticky="w", pady=5, padx=(0, 10))
if field_name == "gender":
# Create gender dropdown
self.entries[field_name] = ttk.Combobox(parent, values=["Male", "Female", "Other"],
state="readonly", width=22)
else:
self.entries[field_name] = Entry(parent, font=("Arial", 10), width=25)
self.entries[field_name].grid(row=i+1, column=1, pady=5)
def create_buttons(self, parent):
button_frame = Frame(parent, bg="#f0f0f0")
button_frame.grid(row=7, column=0, columnspan=2, pady=20)
submit_btn = Button(button_frame, text="Submit", command=self.submit_form,
bg="#4CAF50", fg="white", font=("Arial", 10, "bold"),
padx=20, pady=5)
submit_btn.pack(side=LEFT, padx=5)
clear_btn = Button(button_frame, text="Clear", command=self.clear_form,
bg="#f44336", fg="white", font=("Arial", 10, "bold"),
padx=20, pady=5)
clear_btn.pack(side=LEFT, padx=5)
def validate_email(self, email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return re.match(pattern, email) is not None
def validate_phone(self, phone):
return phone.isdigit() and len(phone) >= 10
def submit_form(self):
# Get all values
values = {}
for field, entry in self.entries.items():
values[field] = entry.get().strip()
# Validate required fields
if not all(values.values()):
messagebox.showerror("Error", "Please fill all fields")
return
# Validate email
if not self.validate_email(values['email']):
messagebox.showerror("Error", "Please enter a valid email address")
return
# Validate phone
if not self.validate_phone(values['phone']):
messagebox.showerror("Error", "Please enter a valid phone number (min 10 digits)")
return
# Validate age
try:
age = int(values['age'])
if age < 1 or age > 120:
raise ValueError
except ValueError:
messagebox.showerror("Error", "Please enter a valid age (1-120)")
return
# Show success message
messagebox.showinfo("Success",
f"Registration successful!\n\n"
f"Name: {values['first_name']} {values['last_name']}\n"
f"Email: {values['email']}\n"
f"Phone: {values['phone']}")
self.clear_form()
def clear_form(self):
for entry in self.entries.values():
if isinstance(entry, Entry):
entry.delete(0, END)
else: # Combobox
entry.set('')
# Create and run the application
if __name__ == "__main__":
root = Tk()
app = RegistrationForm(root)
root.mainloop()
Key Features of the Registration Form
- Input Validation ? Validates email format, phone number, and age
- User-friendly Interface ? Clean layout with proper spacing and colors
- Error Handling ? Shows appropriate error messages for invalid inputs
- Form Controls ? Submit and Clear buttons for user interaction
- Dropdown Menu ? Gender selection using Combobox widget
Conclusion
Tkinter provides powerful widgets to create professional registration forms with validation. The grid layout manager helps organize form elements neatly, while messagebox provides user feedback for form submission.
---