Mundo em Python

Login (com base de dados)

import sqlite3
import hashlib
from tkinter import * conn = sqlite3.connect('usuarios2.db')
c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS usuarios (
id INTEGER PRIMARY KEY,
username TEXT NOT NULL,
senha TEXT NOT NULL)''') def cadastrar_usuario():
username = Nome_utilizador.get()
senha = palavra_passe_utilizador.get() c.execute("SELECT * FROM usuarios WHERE username=?", (username,))
if c.fetchone():
mensagem = "Este utilizador já existe!"
else:
senha_hash = hashlib.sha256(senha.encode()).hexdigest()
c.execute("INSERT INTO usuarios (username, senha) VALUES (?, ?)", (username, senha_hash))
conn.commit()
mensagem = "Utilizador registrado com sucesso!"

resultado_texto.config(text=mensagem)
def fazer_login():
username = Nome_utilizador.get()
senha = palavra_passe_utilizador.get() senha_hash = hashlib.sha256(senha.encode()).hexdigest()
c.execute("SELECT * FROM usuarios WHERE username=? AND senha=?", (username, senha_hash))
if c.fetchone():
mensagem = "Login bem-sucedido!"
else:
mensagem = "Credenciais inválidas!"

resultado_texto.config(text=mensagem)
root = Tk()
root.geometry("400x400")
root.resizable(0, 0)
root.config(bg="#103030")
root.title("Login") titulo = Label(text="Login",
font=("Arial", "40", "bold"), bg="#103030", fg="#49e3e3")
titulo.place(relx=0.35, rely=0.05) sub1 = Label(text="Nome do utilizador: ", font=("Arial", "15", "bold"), bg="#103030", fg="#49e3e3")
sub1.place(relx=0.05, rely=0.25)
Nome_utilizador = StringVar()
Nome_utilizador_entrada = Entry(textvariable=Nome_utilizador, font=("Arial", "12", "bold"),
bg="white", fg="blue", justify='center')
Nome_utilizador_entrada.place(relx=0.55, rely=0.26, relwidth=0.38)
Nome_utilizador_entrada.focus() sub2 = Label(text="Palavra-passe: ", font=("Arial", "15", "bold"), bg="#103030", fg="#49e3e3")
sub2.place(relx=0.05, rely=0.43)
palavra_passe_utilizador = StringVar()
palavra_passe_utilizador_entrada = Entry(textvariable=palavra_passe_utilizador, font=("Arial", "12", "bold"),
bg="white", fg="blue", justify='center')
palavra_passe_utilizador_entrada.place(relx=0.55, rely=0.43, relwidth=0.38)
def limpar():
Nome_utilizador_entrada.delete(0, END)
palavra_passe_utilizador_entrada.delete(0, END)
resultado_texto.config(text="")
but1 = Button(text="Adicionar", bd=2, bg='#107db2', fg='white',
font=('verdana', 12, 'bold'), command=cadastrar_usuario)
but1.place(relx=0.1, rely=0.55, relwidth=0.25, relheight=0.1) but2 = Button(text="Login", bd=2, bg='#107db2', fg='white',
font=('verdana', 12, 'bold'), command=fazer_login)
but2.place(relx=0.4, rely=0.55, relwidth=0.25, relheight=0.1) but_limpar = Button(text="Limpar", bd=2, bg='#107db2', fg='white',
font=('verdana', 12, 'bold'), command=limpar)
but_limpar.place(relx=0.7, rely=0.55, relwidth=0.25, relheight=0.1) resultado_texto = Label(font=("Arial", 12, "bold"), bg="#cfe2f3")
resultado_texto.place(relx=0.05, rely=0.7, relwidth=0.9, relheight=0.15) root.mainloop()
0