[Python] custom tkinter and python and sql to make gui

Discussão em 'Python' iniciado por Stack, Março 23, 2025.

  1. Stack

    Stack Membro Participativo

    import tkinter as tk
    import customtkinter as ctk
    import sqlite3
    import re
    import smtplib
    import random
    import string
    import webbrowser
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from PIL import Image, ImageTk
    import os
    from datetime import datetime, timedelta

    # Set appearance mode and color theme
    ctk.set_appearance_mode("System")
    ctk.set_default_color_theme("blue")

    # Database setup
    def setup_database():
    conn = sqlite3.connect('mycompany.db')
    cursor = conn.cursor()

    # Create users table
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    email TEXT UNIQUE NOT NULL,
    password TEXT NOT NULL,
    confirmed INTEGER DEFAULT 0,
    confirmation_code TEXT,
    facebook_linked INTEGER DEFAULT 0
    )
    ''')

    # Create consultations table
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS consultations (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER,
    date TEXT NOT NULL,
    time TEXT NOT NULL,
    description TEXT,
    FOREIGN KEY (user_id) REFERENCES users (id)
    )
    ''')

    # Create articles table
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS articles (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT NOT NULL,
    content TEXT NOT NULL,
    image_path TEXT
    )
    ''')

    # Insert sample articles
    sample_articles = [
    ("Building Your Dream Home", "Learn how our company can help you build the perfect home for your family...", "house1.png"),
    ("Renovating on a Budget", "Discover cost-effective ways to transform your living space...", "house2.png"),
    ("Sustainable Building Practices", "Our commitment to environmentally friendly construction methods...", "house3.png")
    ]

    for article in sample_articles:
    cursor.execute("INSERT OR IGNORE INTO articles (title, content, image_path) VALUES (?, ?, ?)", article)

    conn.commit()
    conn.close()

    # Email sending function
    def send_confirmation_email(email, confirmation_code):
    # In a real application, you would use your actual SMTP server details
    # This is a placeholder function
    print(f"Email sent to {email} with confirmation code: {confirmation_code}")

    # Uncomment and modify the below code to actually send emails
    """
    sender_email = "your_email@example.com"
    sender_password = "your_email_password"

    message = MIMEMultipart()
    message["From"] = sender_email
    message["To"] = email
    message["Subject"] = "My Company - Confirm Your Registration"

    body = f"""
    Hello,

    Thank you for registering with My Company!

    Your confirmation code is: {confirmation_code}

    Please enter this code in the application to complete your registration.

    Best regards,
    My Company Team
    """

    message.attach(MIMEText(body, "plain"))

    try:
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login(sender_email, sender_password)
    server.sendmail(sender_email, email, message.as_string())
    server.quit()
    return True
    except Exception as e:
    print(f"Error sending email: {e}")
    return False
    """
    return True

    # Generate random confirmation code
    def generate_confirmation_code(length=6):
    return ''.join(random.choices(string.ascii_uppercase + string.digits, k=length))

    # Main Application Class
    class MyCompanyApp(ctk.CTk):
    def __init__(self):
    super().__init__()

    # Setup database
    setup_database()

    # Configure window
    self.title("My Company")
    self.geometry("900x600")
    self.minsize(800, 600)

    # Initialize variables
    self.current_user_id = None
    self.current_user_email = None
    self.current_page = None
    self.zoom_level = 100

    # Create home page as default
    self.show_home_page()

    def clear_window(self):
    for widget in self.winfo_children():
    widget.destroy()

    def show_home_page(self):
    self.clear_window()
    self.current_page = "home"

    # Create a frame for the header
    header_frame = ctk.CTkFrame(self)
    header_frame.pack(fill="x", padx=10, pady=10)

    # Company logo and title
    logo_label = ctk.CTkLabel(header_frame, text="", font=ctk.CTkFont(size=30))
    logo_label.pack(side="left", padx=10)

    title_label = ctk.CTkLabel(header_frame, text="My Company", font=ctk.CTkFont(size=24, weight="bold"))
    title_label.pack(side="left", padx=10)

    # Zoom buttons
    zoom_frame = ctk.CTkFrame(header_frame)
    zoom_frame.pack(side="right", padx=10)

    zoom_out_btn = ctk.CTkButton(zoom_frame, text="➖", width=30, command=self.zoom_out)
    zoom_out_btn.pack(side="left", padx=5)

    self.zoom_label = ctk.CTkLabel(zoom_frame, text=f"{self.zoom_level}%")
    self.zoom_label.pack(side="left", padx=5)

    zoom_in_btn = ctk.CTkButton(zoom_frame, text="➕", width=30, command=self.zoom_in)
    zoom_in_btn.pack(side="left", padx=5)

    # Navigation buttons
    nav_frame = ctk.CTkFrame(self)
    nav_frame.pack(fill="x", padx=10, pady=5)

    home_btn = ctk.CTkButton(nav_frame, text="Home", command=self.show_home_page)
    home_btn.pack(side="left", padx=5)

    login_btn = ctk.CTkButton(nav_frame, text="Login", command=self.show_login_page)
    login_btn.pack(side="left", padx=5)

    register_btn = ctk.CTkButton(nav_frame, text="Register", command=self.show_register_page)
    register_btn.pack(side="left", padx=5)

    # Main content
    content_frame = ctk.CTkFrame(self)
    content_frame.pack(fill="both", expand=True, padx=10, pady=10)

    # Welcome message
    welcome_label = ctk.CTkLabel(
    content_frame,
    text="Welcome to My Company",
    font=ctk.CTkFont(size=20, weight="bold")
    )
    welcome_label.pack(pady=20)

    intro_text = ctk.CTkLabel(
    content_frame,
    text="We specialize in providing top-notch consultation services.\n"
    "Register or login to book your consultation today!",
    font=ctk.CTkFont(size=14)
    )
    intro_text.pack(pady=10)

    # Articles section
    articles_label = ctk.CTkLabel(
    content_frame,
    text="Latest Articles",
    font=ctk.CTkFont(size=18, weight="bold")
    )
    articles_label.pack(pady=(20, 10))

    # Fetch articles from database
    conn = sqlite3.connect('mycompany.db')
    cursor = conn.cursor()
    cursor.execute("SELECT title, content, image_path FROM articles")
    articles = cursor.fetchall()
    conn.close()

    # Display articles
    articles_frame = ctk.CTkScrollableFrame(content_frame)
    articles_frame.pack(fill="both", expand=True, padx=10, pady=10)

    for i, (title, content, image_path) in enumerate(articles):
    article_frame = ctk.CTkFrame(articles_frame)
    article_frame.pack(fill="x", padx=10, pady=10)

    # Article title
    article_title = ctk.CTkLabel(
    article_frame,
    text=title,
    font=ctk.CTkFont(size=16, weight="bold")
    )
    article_title.pack(pady=(10, 5), padx=10, anchor="w")

    # Article content (truncated)
    article_content = ctk.CTkLabel(
    article_frame,
    text=content[:100] + "..." if len(content) > 100 else content,
    font=ctk.CTkFont(size=12),
    justify="left",
    wraplength=600
    )
    article_content.pack(pady=5, padx=10, anchor="w")

    # Read more button
    read_more_btn = ctk.CTkButton(
    article_frame,
    text="Read More",
    command=lambda t=title, c=content: self.show_article(t, c)
    )
    read_more_btn.pack(pady=10, padx=10, anchor="e")

    def show_article(self, title, content):
    # Create a new window to display the full article
    article_window = ctk.CTkToplevel(self)
    article_window.title(title)
    article_window.geometry("600x400")

    # Article title
    title_label = ctk.CTkLabel(
    article_window,
    text=title,
    font=ctk.CTkFont(size=20, weight="bold")
    )
    title_label.pack(pady=20, padx=20)

    # Article content in scrollable frame
    content_frame = ctk.CTkScrollableFrame(article_window)
    content_frame.pack(fill="both", expand=True, padx=20, pady=20)

    content_label = ctk.CTkLabel(
    content_frame,
    text=content,
    font=ctk.CTkFont(size=14),
    justify="left",
    wraplength=540
    )
    content_label.pack(pady=10, padx=10)

    def show_register_page(self):
    self.clear_window()
    self.current_page = "register"

    # Create a frame for the registration form
    register_frame = ctk.CTkFrame(self)
    register_frame.pack(expand=True, padx=20, pady=20)

    # Title
    title_label = ctk.CTkLabel(
    register_frame,
    text="Register for My Company",
    font=ctk.CTkFont(size=20, weight="bold")
    )
    title_label.pack(pady=20, padx=20)

    # Name field
    name_label = ctk.CTkLabel(register_frame, text="Full Name:")
    name_label.pack(anchor="w", padx=20, pady=(10, 0))

    name_entry = ctk.CTkEntry(register_frame, width=300)
    name_entry.pack(padx=20, pady=(0, 10))

    # Email field
    email_label = ctk.CTkLabel(register_frame, text="Email:")
    email_label.pack(anchor="w", padx=20, pady=(10, 0))

    email_entry = ctk.CTkEntry(register_frame, width=300)
    email_entry.pack(padx=20, pady=(0, 10))

    # Password field
    password_label = ctk.CTkLabel(register_frame, text="Password:")
    password_label.pack(anchor="w", padx=20, pady=(10, 0))

    password_entry = ctk.CTkEntry(register_frame, width=300, show="*")
    password_entry.pack(padx=20, pady=(0, 10))

    # Confirm password field
    confirm_password_label = ctk.CTkLabel(register_frame, text="Confirm Password:")
    confirm_password_label.pack(anchor="w", padx=20, pady=(10, 0))

    confirm_password_entry = ctk.CTkEntry(register_frame, width=300, show="*")
    confirm_password_entry.pack(padx=20, pady=(0, 10))

    # Message label for feedback
    message_label = ctk.CTkLabel(register_frame, text="")
    message_label.pack(pady=10)

    # Register button
    def register():
    name = name_entry.get().strip()
    email = email_entry.get().strip()
    password = password_entry.get()
    confirm_password = confirm_password_entry.get()

    # Form validation
    if not name or not email or not password or not confirm_password:
    message_label.configure(text="All fields are required", text_color="red")
    return

    # Email validation
    if not re.match(r"[^@]+@[^@]+\.[^@]+", email):
    message_label.configure(text="Invalid email format", text_color="red")
    return

    # Password validation
    if password != confirm_password:
    message_label.configure(text="Passwords do not match", text_color="red")
    return

    if len(password) < 6:
    message_label.configure(text="Password must be at least 6 characters", text_color="red")
    return

    # Check if email already exists
    conn = sqlite3.connect('mycompany.db')
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM users WHERE email=?", (email,))
    user = cursor.fetchone()

    if user:
    conn.close()
    message_label.configure(text="Email already registered", text_color="red")
    return

    # Generate confirmation code
    confirmation_code = generate_confirmation_code()

    # Insert user into database
    cursor.execute(
    "INSERT INTO users (name, email, password, confirmation_code) VALUES (?, ?, ?, ?)",
    (name, email, password, confirmation_code)
    )
    conn.commit()
    conn.close()

    # Send confirmation email
    if send_confirmation_email(email, confirmation_code):
    # Show confirmation code entry screen
    self.show_confirm_email_page(email)
    else:
    message_label.configure(text="Failed to send confirmation email", text_color="red")

    register_btn = ctk.CTkButton(register_frame, text="Register", command=register)
    register_btn.pack(pady=20)

    # Back to login button
    back_btn = ctk.CTkButton(
    register_frame,
    text="Already have an account? Login",
    command=self.show_login_page,
    fg_color="transparent",
    text_color=("blue", "light blue")
    )
    back_btn.pack(pady=10)

    # Back to home button
    home_btn = ctk.CTkButton(
    register_frame,
    text="Back to Home",
    command=self.show_home_page,
    fg_color="transparent",
    text_color=("blue", "light blue")
    )
    home_btn.pack(pady=10)

    def show_confirm_email_page(self, email):
    self.clear_window()
    self.current_page = "confirm_email"

    confirm_frame = ctk.CTkFrame(self)
    confirm_frame.pack(expand=True, padx=20, pady=20)

    # Title
    title_label = ctk.CTkLabel(
    confirm_frame,
    text="Confirm Your Email",
    font=ctk.CTkFont(size=20, weight="bold")
    )
    title_label.pack(pady=20, padx=20)

    # Instructions
    instructions_label = ctk.CTkLabel(
    confirm_frame,
    text=f"We've sent a confirmation code to {email}.\nPlease enter the code below to complete your registration.",
    font=ctk.CTkFont(size=14)
    )
    instructions_label.pack(pady=10, padx=20)

    # Confirmation code field
    code_label = ctk.CTkLabel(confirm_frame, text="Confirmation Code:")
    code_label.pack(anchor="w", padx=20, pady=(10, 0))

    code_entry = ctk.CTkEntry(confirm_frame, width=200)
    code_entry.pack(padx=20, pady=(0, 10))

    # Message label for feedback
    message_label = ctk.CTkLabel(confirm_frame, text="")
    message_label.pack(pady=10)

    # Confirm button
    def confirm_code():
    code = code_entry.get().strip()

    if not code:
    message_label.configure(text="Please enter the confirmation code", text_color="red")
    return

    # Verify code
    conn = sqlite3.connect('mycompany.db')
    cursor = conn.cursor()
    cursor.execute("SELECT id FROM users WHERE email=? AND confirmation_code=?", (email, code))
    user = cursor.fetchone()

    if user:
    # Update user as confirmed
    cursor.execute("UPDATE users SET confirmed=1 WHERE email=?", (email,))
    conn.commit()
    conn.close()

    message_label.configure(text="Email confirmed successfully!", text_color="green")

    # Redirect to login page after a delay
    self.after(2000, self.show_login_page)
    else:
    conn.close()
    message_label.configure(text="Invalid confirmation code", text_color="red")

    confirm_btn = ctk.CTkButton(confirm_frame, text="Confirm", command=confirm_code)
    confirm_btn.pack(pady=20)

    # Resend code button
    def resend_code():
    # Generate new confirmation code
    new_code = generate_confirmation_code()

    # Update code in database
    conn = sqlite3.connect('mycompany.db')
    cursor = conn.cursor()
    cursor.execute("UPDATE users SET confirmation_code=? WHERE email=?", (new_code, email))
    conn.commit()
    conn.close()

    # Resend email
    if send_confirmation_email(email, new_code):
    message_label.configure(text="Confirmation code resent", text_color="green")
    else:
    message_label.configure(text="Failed to resend confirmation code", text_color="red")

    resend_btn = ctk.CTkButton(
    confirm_frame,
    text="Resend Code",
    command=resend_code,
    fg_color="transparent",
    text_color=("blue", "light blue")
    )
    resend_btn.pack(pady=10)

    # Back to home button
    home_btn = ctk.CTkButton(
    confirm_frame,
    text="Back to Home",
    command=self.show_home_page,
    fg_color="transparent",
    text_color=("blue", "light blue")
    )
    home_btn.pack(pady=10)

    def show_login_page(self):
    self.clear_window()
    self.current_page = "login"

    # Create a frame for the login form
    login_frame = ctk.CTkFrame(self)
    login_frame.pack(expand=True, padx=20, pady=20)

    # Title
    title_label = ctk.CTkLabel(
    login_frame,
    text="Login to My Company",
    font=ctk.CTkFont(size=20, weight="bold")
    )
    title_label.pack(pady=20, padx=20)

    # Email field
    email_label = ctk.CTkLabel(login_frame, text="Email:")
    email_label.pack(anchor="w", padx=20, pady=(10, 0))

    email_entry = ctk.CTkEntry(login_frame, width=300)
    email_entry.pack(padx=20, pady=(0, 10))

    # Password field
    password_label = ctk.CTkLabel(login_frame, text="Password:")
    password_label.pack(anchor="w", padx=20, pady=(10, 0))

    password_entry = ctk.CTkEntry(login_frame, width=300, show="*")
    password_entry.pack(padx=20, pady=(0, 10))

    # Message label for feedback
    message_label = ctk.CTkLabel(login_frame, text="")
    message_label.pack(pady=10)

    # Login button
    def login():
    email = email_entry.get().strip()
    password = password_entry.get()

    # Form validation
    if not email or not password:
    message_label.configure(text="Please enter both email and password", text_color="red")
    return

    # Check credentials
    conn = sqlite3.connect('mycompany.db')
    cursor = conn.cursor()
    cursor.execute("SELECT id, confirmed FROM users WHERE email=? AND password=?", (email, password))
    user = cursor.fetchone()
    conn.close()

    if not user:
    message_label.configure(text="Invalid email or password", text_color="red")
    return

    user_id, confirmed = user

    if not confirmed:
    message_label.configure(text="Please confirm your email first", text_color="red")
    self.after(2000, lambda: self.show_confirm_email_page(email))
    return

    # Set current user and show account page
    self.current_user_id = user_id
    self.current_user_email = email
    self.show_account_page()

    login_btn = ctk.CTkButton(login_frame, text="Login", command=login)
    login_btn.pack(pady=20)

    # Social media login section
    social_label = ctk.CTkLabel(login_frame, text="Or connect with:")
    social_label.pack(pady=(20, 10))

    social_frame = ctk.CTkFrame(login_frame, fg_color="transparent")
    social_frame.pack(pady=10)

    def connect_facebook():
    if not self.current_user_id:
    message_label.configure(text="Please login first", text_color="red")
    return

    # In a real app, this would redirect to Facebook OAuth
    # For this demo, we'll just open Facebook and simulate linking
    webbrowser.open("https://www.facebook.com")

    # Simulate successful linking
    conn = sqlite3.connect('mycompany.db')
    cursor = conn.cursor()
    cursor.execute("UPDATE users SET facebook_linked=1 WHERE id=?", (self.current_user_id,))
    conn.commit()
    conn.close()

    message_label.configure(text="Facebook account linked successfully", text_color="green")

    facebook_btn = ctk.CTkButton(
    social_frame,
    text="Facebook",
    command=connect_facebook,
    fg_color="#1877F2",
    hover_color="#0e5dc6"
    )
    facebook_btn.pack(side="left", padx=10)

    # Register button
    register_btn = ctk.CTkButton(
    login_frame,
    text="Don't have an account? Register",
    command=self.show_register_page,
    fg_color="transparent",
    text_color=("blue", "light blue")
    )
    register_btn.pack(pady=10)

    # Back to home button
    home_btn = ctk.CTkButton(
    login_frame,
    text="Back to Home",
    command=self.show_home_page,
    fg_color="transparent",
    text_color=("blue", "light blue")
    )
    home_btn.pack(pady=10)

    def show_account_page(self):
    self.clear_window()
    self.current_page = "account"

    # Get user info
    conn = sqlite3.connect('mycompany.db')
    cursor = conn.cursor()
    cursor.execute("SELECT name, email, facebook_linked FROM users WHERE id=?", (self.current_user_id,))
    user = cursor.fetchone()
    conn.close()

    if not user:
    self.show_login_page()
    return

    name, email, facebook_linked = user

    # Create main frame
    main_frame = ctk.CTkFrame(self)
    main_frame.pack(fill="both", expand=True, padx=10, pady=10)

    # Create sidebar for navigation
    sidebar = ctk.CTkFrame(main_frame, width=200)
    sidebar.pack(side="left", fill="y", padx=10, pady=10)

    # User info in sidebar
    user_frame = ctk.CTkFrame(sidebar)
    user_frame.pack(fill="x", padx=10, pady=10)

    # User icon
    user_icon = ctk.CTkLabel(user_frame, text="", font=ctk.CTkFont(size=30))
    user_icon.pack(pady=10)

    # User name
    name_label = ctk.CTkLabel(
    user_frame,
    text=name,
    font=ctk.CTkFont(size=16, weight="bold")
    )
    name_label.pack(pady=5)

    # User email
    email_label = ctk.CTkLabel(
    user_frame,
    text=email,
    font=ctk.CTkFont(size=12)
    )
    email_label.pack(pady=5)

    # Connected accounts
    if facebook_linked:
    fb_label = ctk.CTkLabel(
    user_frame,
    text="✓ Facebook Connected",
    font=ctk.CTkFont(size=12),
    text_color="green"
    )
    fb_label.pack(pady=5)


    This a gui making a website about a company, When user is in my account allow user to book and cancel consultations and make.In the home page have the title my company and the logo is a house and font should be clear and have a zoom in and out option In the home page should link articles about companies and have clear images

    Continue reading...

Compartilhe esta Página