Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Compilar com pyinstaller --windowed --hidden-import babel.numbers --hidden-import babel.localedata nome_do_arquivo.py
- import tkinter as tk
- from tkinter import ttk, messagebox
- import sqlite3
- import pyperclip
- import webbrowser
- from tkcalendar import DateEntry # Para o calendário
- from reportlab.lib.pagesizes import letter
- from reportlab.pdfgen import canvas
- class Application(tk.Tk):
- def __init__(self):
- super().__init__()
- self.title("Cadastro de Filmes")
- self.geometry("1000x600")
- self.init_db()
- self.create_widgets()
- self.create_menu()
- self.center_window()
- def create_widgets(self):
- self.search_var = tk.StringVar()
- self.search_entry = ttk.Entry(self, textvariable=self.search_var)
- self.search_entry.pack(pady=(0, 10))
- # Adicionado: bind para o evento "Enter"
- self.search_entry.bind("<Return>", lambda event: self.search_records())
- self.search_button = ttk.Button(self, text="Pesquisar", command=self.search_records)
- self.search_button.pack(pady=(0, 10))
- # Adicionado botão "Atualizar" para mostrar todos os registros
- self.refresh_button = ttk.Button(self, text="Atualizar", command=self.refresh_tree)
- self.refresh_button.pack(pady=(0, 10))
- # Atualizado: Removido o campo "Sinopse"
- self.tree = ttk.Treeview(self, columns=("Nome", "Gênero", "URL", "Data"), show="headings")
- self.tree.heading("Nome", text="Nome")
- self.tree.heading("Gênero", text="Gênero")
- self.tree.heading("URL", text="URL")
- self.tree.heading("Data", text="Data")
- 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 Filme", command=self.add_entry)
- self.add_button.pack()
- self.edit_button = ttk.Button(self, text="Editar Filme", command=self.edit_entry)
- self.edit_button.pack()
- self.delete_button = ttk.Button(self, text="Excluir Filme", 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.tree.bind("<Button-3>", self.popup_menu)
- self.tree.bind("<Double-1>", self.open_url)
- self.load_data()
- 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 init_db(self):
- self.conn = sqlite3.connect("filmes.db")
- self.cursor = self.conn.cursor()
- self.cursor.execute("""
- CREATE TABLE IF NOT EXISTS filmes (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- nome TEXT,
- genero TEXT,
- url TEXT,
- data TEXT
- )
- """)
- self.conn.commit()
- def load_data(self):
- self.cursor.execute("SELECT nome, genero, url, data FROM filmes")
- for row in self.cursor.fetchall():
- self.tree.insert("", "end", values=row)
- def save_data(self):
- self.cursor.execute("DELETE FROM filmes")
- for item in self.tree.get_children():
- values = self.tree.item(item, "values")
- self.cursor.execute("INSERT INTO filmes (nome, genero, url, data) 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]
- nome = self.tree.item(selected_item, "values")[0]
- self.cursor.execute("DELETE FROM filmes WHERE nome=?", (nome,))
- self.conn.commit()
- self.tree.delete(selected_item)
- def confirm_delete(self):
- try:
- if messagebox.askyesno("Confirmar", "Tem certeza que deseja excluir este filme?"):
- 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(2))
- 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 open_url(self, event):
- if self.tree.selection():
- item = self.tree.selection()[0]
- url = self.tree.item(item, "values")[2]
- webbrowser.open(url)
- def search_records(self):
- search_term = self.search_var.get().strip().lower()
- if not search_term:
- messagebox.showinfo("Pesquisa", "Digite um termo de pesquisa.")
- return
- for item in self.tree.get_children():
- self.tree.delete(item)
- self.cursor.execute("""
- SELECT nome, genero, url, data FROM filmes
- WHERE lower(nome) LIKE ? OR lower(genero) LIKE ?
- """, ('%' + search_term + '%', '%' + search_term + '%'))
- found = False
- for row in self.cursor.fetchall():
- self.tree.insert("", "end", values=row)
- found = True
- if not found:
- messagebox.showinfo("Pesquisa", "Nenhum registro correspondente encontrado.")
- self.refresh_tree()
- def export_to_pdf(self):
- file_name = "filmes_cadastrados.pdf"
- c = canvas.Canvas(file_name, pagesize=letter)
- c.setFont("Helvetica", 10)
- y_position = 750
- for item in self.tree.get_children():
- values = self.tree.item(item, "values")
- c.drawString(100, y_position, f"Nome: {values[0]}, Gênero: {values[1]}, Data: {values[3]}")
- y_position -= 20
- c.save()
- messagebox.showinfo("Exportação de dados", f"Arquivo {file_name} foi gerado com sucesso.")
- def show_about_dialog(self):
- messagebox.showinfo("Sobre", "Gerenciador de Filmes v1.0")
- def quit_app(self):
- self.conn.close()
- self.destroy()
- 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}')
- class AddEntryWindow(tk.Toplevel):
- def __init__(self, parent):
- super().__init__(parent)
- self.title("Adicionar Filme")
- self.geometry("400x300")
- self.create_widgets()
- self.center_window()
- def create_widgets(self):
- self.nome_label = ttk.Label(self, text="Nome:")
- self.nome_label.pack(pady=5)
- self.nome_entry = ttk.Entry(self, width=50) # Aumentado
- self.nome_entry.pack(pady=5)
- self.genero_label = ttk.Label(self, text="Gênero:")
- self.genero_label.pack(pady=5)
- self.genero_entry = ttk.Entry(self, width=50) # Aumentado
- self.genero_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) # Aumentado
- self.url_entry.pack(pady=5)
- self.data_label = ttk.Label(self, text="Data:")
- self.data_label.pack(pady=5)
- self.data_entry = DateEntry(self, date_pattern='dd/mm/yyyy')
- self.data_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):
- nome = self.nome_entry.get().strip()
- genero = self.genero_entry.get().strip()
- url = self.url_entry.get().strip()
- data = self.data_entry.get()
- if nome and genero and url and data:
- self.master.cursor.execute("INSERT INTO filmes (nome, genero, url, data) VALUES (?, ?, ?, ?)",
- (nome, genero, url, data))
- self.master.conn.commit()
- self.master.refresh_tree()
- self.destroy()
- else:
- messagebox.showerror("Erro", "Todos os campos devem ser preenchidos.")
- class EditEntryWindow(AddEntryWindow):
- def __init__(self, parent, values):
- super().__init__(parent)
- self.values = values
- self.fill_fields()
- def fill_fields(self):
- self.nome_entry.insert(0, self.values[0])
- self.genero_entry.insert(0, self.values[1])
- self.url_entry.insert(0, self.values[2])
- self.data_entry.set_date(self.values[3])
- def save_entry(self):
- nome = self.nome_entry.get().strip()
- genero = self.genero_entry.get().strip()
- url = self.url_entry.get().strip()
- data = self.data_entry.get()
- if nome and genero and url and data:
- selected_item = self.master.tree.selection()[0]
- self.master.cursor.execute("""
- UPDATE filmes
- SET nome = ?, genero = ?, url = ?, data = ?
- WHERE nome = ?
- """, (nome, genero, url, data, self.values[0]))
- self.master.conn.commit()
- self.master.refresh_tree()
- self.destroy()
- else:
- messagebox.showerror("Erro", "Todos os campos devem ser preenchidos.")
- if __name__ == "__main__":
- app = Application()
- app.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement