Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import tkinter as tk
- from tkinter import ttk, messagebox
- import sqlite3
- import pyperclip
- import webbrowser
- from reportlab.lib.pagesizes import letter, landscape
- from reportlab.pdfgen import canvas
- class Application(tk.Tk):
- def __init__(self):
- super().__init__()
- self.title("Gerenciador de Senhas de Sites - Versão 5.5")
- self.geometry("1000x600")
- self.sort_order_site = "asc"
- self.sort_order_login = "asc"
- self.init_db()
- self.create_widgets()
- self.create_menu()
- self.date_label = ttk.Label(self, text="Mizuno - 02/11/2024")
- self.date_label.place(x=10, y=self.winfo_height() - 30)
- self.center_window()
- def create_widgets(self):
- self.search_var = tk.StringVar()
- self.search_entry = ttk.Entry(self, textvariable=self.search_var, width=50)
- self.search_entry.pack(pady=(0, 10))
- # Vincula o evento KeyRelease para busca em tempo real
- self.search_entry.bind("<KeyRelease>", lambda event: self.search_records())
- self.search_button = ttk.Button(self, text="Pesquisar", command=self.search_records)
- self.search_button.pack(pady=(0, 10))
- # Botão Atualizar com o mesmo comportamento do código 1
- self.refresh_button = ttk.Button(self, text="Atualizar", command=self.refresh_tree)
- self.refresh_button.pack(pady=(0, 10))
- self.tree = ttk.Treeview(self, columns=("Site", "URL", "Login", "Senha"), show="headings")
- self.tree.heading("Site", text="Site", command=self.sort_sites)
- self.tree.heading("URL", text="URL")
- self.tree.heading("Login", text="Login", command=self.sort_login)
- self.tree.heading("Senha", text="Senha")
- self.tree.pack(pady=10, side="left", fill="both", expand=True)
- scrollbar = ttk.Scrollbar(self, orient="vertical", command=self.tree.yview)
- scrollbar.pack(side="right", fill="y")
- self.tree.configure(yscrollcommand=scrollbar.set)
- self.add_button = ttk.Button(self, text="Adicionar", command=self.add_entry)
- self.add_button.pack()
- self.edit_button = ttk.Button(self, text="Editar", command=self.edit_entry)
- self.edit_button.pack()
- self.delete_button = ttk.Button(self, text="Excluir", command=self.confirm_delete)
- self.delete_button.pack()
- self.pdf_button = ttk.Button(self, text="Exportar PDF", command=self.export_to_pdf)
- self.pdf_button.pack()
- self.load_data()
- self.tree.bind("<Button-3>", self.popup_menu)
- self.tree.bind("<Double-1>", self.open_url)
- def create_menu(self):
- self.menu_bar = tk.Menu(self)
- self.file_menu = tk.Menu(self.menu_bar, tearoff=0)
- self.file_menu.add_command(label="Sobre", command=self.show_about_dialog)
- self.file_menu.add_separator()
- self.file_menu.add_command(label="Sair", command=self.quit_app)
- self.menu_bar.add_cascade(label="Arquivo", menu=self.file_menu)
- self.config(menu=self.menu_bar)
- def open_url(self, event):
- if self.tree.selection():
- item = self.tree.selection()[0]
- url = self.tree.item(item, "values")[1]
- webbrowser.open(url)
- def center_window(self):
- self.update_idletasks()
- width = self.winfo_width()
- height = self.winfo_height()
- x = (self.winfo_screenwidth() - width) // 2
- y = (self.winfo_screenheight() - height) // 2
- self.geometry(f'{width}x{height}+{x}+{y}')
- def init_db(self):
- self.conn = sqlite3.connect("dados.db")
- self.cursor = self.conn.cursor()
- self.cursor.execute("""
- CREATE TABLE IF NOT EXISTS senhas (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- site TEXT,
- url TEXT,
- login TEXT,
- senha TEXT
- )
- """)
- self.conn.commit()
- def load_data(self):
- self.cursor.execute("SELECT site, url, login, senha FROM senhas")
- for row in self.cursor.fetchall():
- self.tree.insert("", "end", values=row)
- def save_data(self):
- self.cursor.execute("DELETE FROM senhas")
- for item in self.tree.get_children():
- values = self.tree.item(item, "values")
- self.cursor.execute("INSERT INTO senhas (site, url, login, senha) VALUES (?, ?, ?, ?)", values)
- self.conn.commit()
- def refresh_tree(self):
- for item in self.tree.get_children():
- self.tree.delete(item)
- self.load_data()
- def add_entry(self):
- AddEntryWindow(self)
- def edit_entry(self):
- try:
- item = self.tree.selection()[0]
- values = self.tree.item(item, "values")
- EditEntryWindow(self, values)
- except IndexError:
- messagebox.showerror("Erro", "Selecione um registro para editar.")
- def delete_entry(self):
- selected_item = self.tree.selection()[0]
- site = self.tree.item(selected_item, "values")[0]
- self.cursor.execute("DELETE FROM senhas WHERE site=?", (site,))
- self.conn.commit()
- self.tree.delete(selected_item)
- def confirm_delete(self):
- try:
- if messagebox.askyesno("Confirmar", "Tem certeza que deseja excluir este registro?"):
- self.delete_entry()
- except IndexError:
- messagebox.showerror("Erro", "Selecione um registro para excluir.")
- def popup_menu(self, event):
- popup_menu = tk.Menu(self, tearoff=0)
- popup_menu.add_command(label="Copiar URL", command=lambda: self.copy_to_clipboard(1))
- popup_menu.add_command(label="Copiar Login", command=lambda: self.copy_to_clipboard(2))
- popup_menu.add_command(label="Copiar Senha", command=lambda: self.copy_to_clipboard(3))
- popup_menu.post(event.x_root, event.y_root)
- def copy_to_clipboard(self, column_index):
- item = self.tree.selection()[0]
- value = self.tree.item(item, "values")[column_index]
- pyperclip.copy(value)
- def sort_sites(self):
- items = self.tree.get_children("")
- if self.sort_order_site == "asc":
- sorted_items = sorted(items, key=lambda x: self.tree.item(x, "values")[0])
- self.sort_order_site = "desc"
- else:
- sorted_items = sorted(items, key=lambda x: self.tree.item(x, "values")[0], reverse=True)
- self.sort_order_site = "asc"
- for item in sorted_items:
- self.tree.move(item, "", "end")
- def sort_login(self):
- items = self.tree.get_children("")
- if self.sort_order_login == "asc":
- sorted_items = sorted(items, key=lambda x: self.tree.item(x, "values")[2])
- self.sort_order_login = "desc"
- else:
- sorted_items = sorted(items, key=lambda x: self.tree.item(x, "values")[2], reverse=True)
- self.sort_order_login = "asc"
- for item in sorted_items:
- self.tree.move(item, "", "end")
- def show_about_dialog(self):
- messagebox.showinfo("Sobre", "Filtre os dados por Site ou por Login ou pesquise na caixa de texto.\n\nVersão 5.5 - Última atualização: 02/11/2024, Mizuno.")
- def quit_app(self):
- self.conn.close()
- self.destroy()
- def search_records(self):
- search_term = self.search_var.get().strip().lower()
- # Limpa a TreeView antes de preencher com os resultados da pesquisa
- for item in self.tree.get_children():
- self.tree.delete(item)
- # Se não houver termo de pesquisa, exibe todos os registros
- if not search_term:
- self.load_data()
- return
- # Realiza a consulta de acordo com o termo de pesquisa
- self.cursor.execute("""
- SELECT site, url, login, senha FROM senhas
- WHERE lower(site) LIKE ? OR lower(url) LIKE ? OR lower(login) LIKE ?
- """, ('%' + search_term + '%', '%' + search_term + '%', '%' + search_term + '%'))
- for row in self.cursor.fetchall():
- self.tree.insert("", "end", values=row)
- def export_to_pdf(self):
- file_name = "informacoes_exportadas.pdf"
- c = canvas.Canvas(file_name, pagesize=landscape(letter))
- c.setFont("Helvetica", 10)
- x_position = 40
- y_position = 550
- headers = ["Site", "URL", "Login", "Senha"]
- for header in headers:
- c.drawString(x_position, y_position, header)
- x_position += 200
- y_position -= 20
- x_position = 40
- for item in self.tree.get_children():
- if y_position < 40:
- c.showPage()
- c.setFont("Helvetica", 10)
- y_position = 550
- x_position = 40
- for header in headers:
- c.drawString(x_position, y_position, header)
- x_position += 200
- y_position -= 20
- x_position = 40
- values = self.tree.item(item, "values")
- for value in values:
- c.drawString(x_position, y_position, str(value))
- x_position += 200
- y_position -= 20
- x_position = 40
- c.save()
- messagebox.showinfo("Exportação de dados", f"Arquivo {file_name} foi gerado com sucesso.")
- class AddEntryWindow(tk.Toplevel):
- def __init__(self, parent):
- super().__init__(parent)
- self.title("Adicionar Entrada")
- self.geometry("400x300")
- self.create_widgets()
- self.center_window()
- def create_widgets(self):
- self.site_label = ttk.Label(self, text="Site:")
- self.site_label.pack(pady=5)
- self.site_entry = ttk.Entry(self, width=50)
- self.site_entry.pack(pady=5)
- self.url_label = ttk.Label(self, text="URL:")
- self.url_label.pack(pady=5)
- self.url_entry = ttk.Entry(self, width=50)
- self.url_entry.pack(pady=5)
- self.login_label = ttk.Label(self, text="Login:")
- self.login_label.pack(pady=5)
- self.login_entry = ttk.Entry(self, width=50)
- self.login_entry.pack(pady=5)
- self.senha_label = ttk.Label(self, text="Senha:")
- self.senha_label.pack(pady=5)
- self.senha_entry = ttk.Entry(self, width=50)
- self.senha_entry.pack(pady=5)
- self.save_button = ttk.Button(self, text="Salvar", command=self.save_entry)
- self.save_button.pack(pady=20)
- def center_window(self):
- self.update_idletasks()
- width = self.winfo_width()
- height = self.winfo_height()
- x = (self.winfo_screenwidth() - width) // 2
- y = (self.winfo_screenheight() - height) // 2
- self.geometry(f'{width}x{height}+{x}+{y}')
- def save_entry(self):
- site = self.site_entry.get().strip()
- url = self.url_entry.get().strip()
- login = self.login_entry.get().strip()
- senha = self.senha_entry.get().strip()
- if site and url and login and senha:
- self.master.cursor.execute("INSERT INTO senhas (site, url, login, senha) VALUES (?, ?, ?, ?)",
- (site, url, login, senha))
- self.master.conn.commit()
- self.master.refresh_tree()
- self.destroy()
- else:
- messagebox.showerror("Erro", "Todos os campos devem ser preenchidos.")
- class EditEntryWindow(tk.Toplevel):
- def __init__(self, parent, values):
- super().__init__(parent)
- self.title("Editar Entrada")
- self.geometry("400x300")
- self.values = values
- self.create_widgets()
- self.center_window()
- def create_widgets(self):
- self.site_label = ttk.Label(self, text="Site:")
- self.site_label.pack(pady=5)
- self.site_entry = ttk.Entry(self, width=50)
- self.site_entry.pack(pady=5)
- self.site_entry.insert(0, self.values[0])
- self.url_label = ttk.Label(self, text="URL:")
- self.url_label.pack(pady=5)
- self.url_entry = ttk.Entry(self, width=50)
- self.url_entry.pack(pady=5)
- self.url_entry.insert(0, self.values[1])
- self.login_label = ttk.Label(self, text="Login:")
- self.login_label.pack(pady=5)
- self.login_entry = ttk.Entry(self, width=50)
- self.login_entry.pack(pady=5)
- self.login_entry.insert(0, self.values[2])
- self.senha_label = ttk.Label(self, text="Senha:")
- self.senha_label.pack(pady=5)
- self.senha_entry = ttk.Entry(self, width=50)
- self.senha_entry.pack(pady=5)
- self.senha_entry.insert(0, self.values[3])
- self.save_button = ttk.Button(self, text="Salvar", command=self.save_entry)
- self.save_button.pack(pady=20)
- def center_window(self):
- self.update_idletasks()
- width = self.winfo_width()
- height = self.winfo_height()
- x = (self.winfo_screenwidth() - width) // 2
- y = (self.winfo_screenheight() - height) // 2
- self.geometry(f'{width}x{height}+{x}+{y}')
- def save_entry(self):
- site = self.site_entry.get().strip()
- url = self.url_entry.get().strip()
- login = self.login_entry.get().strip()
- senha = self.senha_entry.get().strip()
- if site and url and login and senha:
- selected_item = self.master.tree.selection()[0]
- self.master.cursor.execute("""
- UPDATE senhas
- SET site = ?, url = ?, login = ?, senha = ?
- WHERE site = ?
- """, (site, url, login, senha, self.values[0]))
- self.master.conn.commit()
- self.master.refresh_tree()
- self.destroy()
- else:
- messagebox.showerror("Erro", "Todos os campos devem ser preenchidos.")
- def main():
- app = Application()
- app.mainloop()
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement