To create a registration form using tkinter and connect it to a MySQL database, you can follow these steps:
Step 1: Import Required Modules
import tkinter as tk
import mysql.connector
Step 2: Create a Connection to MySQL Database
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
Step 3: Create a Cursor Object
mycursor = mydb.cursor()
Step 4: Create a Tkinter Window and Widgets
window = tk.Tk()
window.title("Registration Form")
# Create Labels
tk.Label(window, text="First Name").grid(row=0, column=0)
tk.Label(window, text="Last Name").grid(row=1, column=0)
tk.Label(window, text="Email").grid(row=2, column=0)
tk.Label(window, text="Password").grid(row=3, column=0)
# Create Entry Widgets
first_name = tk.Entry(window)
last_name = tk.Entry(window)
email = tk.Entry(window)
password = tk.Entry(window, show="*")
# Position Entry Widgets
first_name.grid(row=0, column=1)
last_name.grid(row=1, column=1)
email.grid(row=2, column=1)
password.grid(row=3, column=1)
Step 5: Define a Function to Submit Data to MySQL Database
def submit():
sql = "INSERT INTO users (first_name, last_name, email, password) VALUES (%s, %s, %s, %s)"
values = (first_name.get(), last_name.get(), email.get(), password.get())
mycursor.execute(sql, values)
mydb.commit()
print("Data Submitted!")
Step 6: Create a Submit Button and Call the Submit Function
submit_button = tk.Button(window, text="Submit", command=submit)
submit_button.grid(row=4, column=1)
Step 7: Run the Tkinter Window
window.mainloop()
Here is the complete code:
import tkinter as tk
import mysql.connector
# Create Connection to MySQL Database
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# Create Cursor Object
mycursor = mydb.cursor()
# Create Tkinter Window and Widgets
window = tk.Tk()
window.title("Registration Form")
# Create Labels
tk.Label(window, text="First Name").grid(row=0, column=0)
tk.Label(window, text="Last Name").grid(row=1, column=0)
tk.Label(window, text="Email").grid(row=2, column=0)
tk.Label(window, text="Password").grid(row=3, column=0)
# Create Entry Widgets
first_name = tk.Entry(window)
last_name = tk.Entry(window)
email = tk.Entry(window)
password = tk.Entry(window, show="*")
# Position Entry Widgets
first_name.grid(row=0, column=1)
last_name.grid(row=1, column=1)
email.grid(row=2, column=1)
password.grid(row=3, column=1)
# Submit Function
def submit():
sql = "INSERT INTO users (first_name, last_name, email, password) VALUES (%s, %s, %s, %s)"
values = (first_name.get(), last_name.get(), email.get(), password.get())
mycursor.execute(sql, values)
mydb.commit()
print("Data Submitted