Advertisement
MizunoBrasil

Cadastro de Filmes OK

Sep 15th, 2024 (edited)
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.63 KB | None | 0 0
  1. # Compilar com pyinstaller --windowed --hidden-import babel.numbers --hidden-import babel.localedata nome_do_arquivo.py
  2.  
  3. import tkinter as tk
  4. from tkinter import ttk, messagebox
  5. import sqlite3
  6. import pyperclip
  7. import webbrowser
  8. from tkcalendar import DateEntry  # Para o calendário
  9. from reportlab.lib.pagesizes import letter
  10. from reportlab.pdfgen import canvas
  11.  
  12.  
  13. class Application(tk.Tk):
  14.     def __init__(self):
  15.         super().__init__()
  16.         self.title("Cadastro de Filmes")
  17.         self.geometry("1000x600")
  18.         self.init_db()
  19.         self.create_widgets()
  20.         self.create_menu()
  21.         self.center_window()
  22.  
  23.     def create_widgets(self):
  24.         self.search_var = tk.StringVar()
  25.         self.search_entry = ttk.Entry(self, textvariable=self.search_var)
  26.         self.search_entry.pack(pady=(0, 10))
  27.  
  28.         # Adicionado: bind para o evento "Enter"
  29.         self.search_entry.bind("<Return>", lambda event: self.search_records())
  30.  
  31.         self.search_button = ttk.Button(self, text="Pesquisar", command=self.search_records)
  32.         self.search_button.pack(pady=(0, 10))
  33.  
  34.         # Adicionado botão "Atualizar" para mostrar todos os registros
  35.         self.refresh_button = ttk.Button(self, text="Atualizar", command=self.refresh_tree)
  36.         self.refresh_button.pack(pady=(0, 10))
  37.  
  38.         # Atualizado: Removido o campo "Sinopse"
  39.         self.tree = ttk.Treeview(self, columns=("Nome", "Gênero", "URL", "Data"), show="headings")
  40.         self.tree.heading("Nome", text="Nome")
  41.         self.tree.heading("Gênero", text="Gênero")
  42.         self.tree.heading("URL", text="URL")
  43.         self.tree.heading("Data", text="Data")
  44.         self.tree.pack(pady=10, side="left", fill="both", expand=True)
  45.  
  46.         scrollbar = ttk.Scrollbar(self, orient="vertical", command=self.tree.yview)
  47.         scrollbar.pack(side="right", fill="y")
  48.         self.tree.configure(yscrollcommand=scrollbar.set)
  49.  
  50.         self.add_button = ttk.Button(self, text="Adicionar Filme", command=self.add_entry)
  51.         self.add_button.pack()
  52.         self.edit_button = ttk.Button(self, text="Editar Filme", command=self.edit_entry)
  53.         self.edit_button.pack()
  54.         self.delete_button = ttk.Button(self, text="Excluir Filme", command=self.confirm_delete)
  55.         self.delete_button.pack()
  56.         self.pdf_button = ttk.Button(self, text="Exportar PDF", command=self.export_to_pdf)
  57.         self.pdf_button.pack()
  58.  
  59.         self.tree.bind("<Button-3>", self.popup_menu)
  60.         self.tree.bind("<Double-1>", self.open_url)
  61.  
  62.         self.load_data()
  63.  
  64.     def create_menu(self):
  65.         self.menu_bar = tk.Menu(self)
  66.         self.file_menu = tk.Menu(self.menu_bar, tearoff=0)
  67.         self.file_menu.add_command(label="Sobre", command=self.show_about_dialog)
  68.         self.file_menu.add_separator()
  69.         self.file_menu.add_command(label="Sair", command=self.quit_app)
  70.         self.menu_bar.add_cascade(label="Arquivo", menu=self.file_menu)
  71.         self.config(menu=self.menu_bar)
  72.  
  73.     def init_db(self):
  74.         self.conn = sqlite3.connect("filmes.db")
  75.         self.cursor = self.conn.cursor()
  76.         self.cursor.execute("""
  77.            CREATE TABLE IF NOT EXISTS filmes (
  78.                id INTEGER PRIMARY KEY AUTOINCREMENT,
  79.                nome TEXT,
  80.                genero TEXT,
  81.                url TEXT,
  82.                data TEXT
  83.            )
  84.        """)
  85.         self.conn.commit()
  86.  
  87.     def load_data(self):
  88.         self.cursor.execute("SELECT nome, genero, url, data FROM filmes")
  89.         for row in self.cursor.fetchall():
  90.             self.tree.insert("", "end", values=row)
  91.  
  92.     def save_data(self):
  93.         self.cursor.execute("DELETE FROM filmes")
  94.         for item in self.tree.get_children():
  95.             values = self.tree.item(item, "values")
  96.             self.cursor.execute("INSERT INTO filmes (nome, genero, url, data) VALUES (?, ?, ?, ?)", values)
  97.         self.conn.commit()
  98.  
  99.     def refresh_tree(self):
  100.         for item in self.tree.get_children():
  101.             self.tree.delete(item)
  102.         self.load_data()
  103.  
  104.     def add_entry(self):
  105.         AddEntryWindow(self)
  106.  
  107.     def edit_entry(self):
  108.         try:
  109.             item = self.tree.selection()[0]
  110.             values = self.tree.item(item, "values")
  111.             EditEntryWindow(self, values)
  112.         except IndexError:
  113.             messagebox.showerror("Erro", "Selecione um registro para editar.")
  114.  
  115.     def delete_entry(self):
  116.         selected_item = self.tree.selection()[0]
  117.         nome = self.tree.item(selected_item, "values")[0]
  118.         self.cursor.execute("DELETE FROM filmes WHERE nome=?", (nome,))
  119.         self.conn.commit()
  120.         self.tree.delete(selected_item)
  121.  
  122.     def confirm_delete(self):
  123.         try:
  124.             if messagebox.askyesno("Confirmar", "Tem certeza que deseja excluir este filme?"):
  125.                 self.delete_entry()
  126.         except IndexError:
  127.             messagebox.showerror("Erro", "Selecione um registro para excluir.")
  128.  
  129.     def popup_menu(self, event):
  130.         popup_menu = tk.Menu(self, tearoff=0)
  131.         popup_menu.add_command(label="Copiar URL", command=lambda: self.copy_to_clipboard(2))
  132.         popup_menu.post(event.x_root, event.y_root)
  133.  
  134.     def copy_to_clipboard(self, column_index):
  135.         item = self.tree.selection()[0]
  136.         value = self.tree.item(item, "values")[column_index]
  137.         pyperclip.copy(value)
  138.  
  139.     def open_url(self, event):
  140.         if self.tree.selection():
  141.             item = self.tree.selection()[0]
  142.             url = self.tree.item(item, "values")[2]
  143.             webbrowser.open(url)
  144.  
  145.     def search_records(self):
  146.         search_term = self.search_var.get().strip().lower()
  147.         if not search_term:
  148.             messagebox.showinfo("Pesquisa", "Digite um termo de pesquisa.")
  149.             return
  150.  
  151.         for item in self.tree.get_children():
  152.             self.tree.delete(item)
  153.  
  154.         self.cursor.execute("""
  155.            SELECT nome, genero, url, data FROM filmes
  156.            WHERE lower(nome) LIKE ? OR lower(genero) LIKE ?
  157.        """, ('%' + search_term + '%', '%' + search_term + '%'))
  158.  
  159.         found = False
  160.         for row in self.cursor.fetchall():
  161.             self.tree.insert("", "end", values=row)
  162.             found = True
  163.  
  164.         if not found:
  165.             messagebox.showinfo("Pesquisa", "Nenhum registro correspondente encontrado.")
  166.             self.refresh_tree()
  167.  
  168.     def export_to_pdf(self):
  169.         file_name = "filmes_cadastrados.pdf"
  170.         c = canvas.Canvas(file_name, pagesize=letter)
  171.         c.setFont("Helvetica", 10)
  172.         y_position = 750
  173.         for item in self.tree.get_children():
  174.             values = self.tree.item(item, "values")
  175.             c.drawString(100, y_position, f"Nome: {values[0]}, Gênero: {values[1]}, Data: {values[3]}")
  176.             y_position -= 20
  177.         c.save()
  178.         messagebox.showinfo("Exportação de dados", f"Arquivo {file_name} foi gerado com sucesso.")
  179.  
  180.     def show_about_dialog(self):
  181.         messagebox.showinfo("Sobre", "Gerenciador de Filmes v1.0")
  182.  
  183.     def quit_app(self):
  184.         self.conn.close()
  185.         self.destroy()
  186.  
  187.     def center_window(self):
  188.         self.update_idletasks()
  189.         width = self.winfo_width()
  190.         height = self.winfo_height()
  191.         x = (self.winfo_screenwidth() - width) // 2
  192.         y = (self.winfo_screenheight() - height) // 2
  193.         self.geometry(f'{width}x{height}+{x}+{y}')
  194.  
  195.  
  196. class AddEntryWindow(tk.Toplevel):
  197.     def __init__(self, parent):
  198.         super().__init__(parent)
  199.         self.title("Adicionar Filme")
  200.         self.geometry("400x300")
  201.         self.create_widgets()
  202.         self.center_window()
  203.  
  204.     def create_widgets(self):
  205.         self.nome_label = ttk.Label(self, text="Nome:")
  206.         self.nome_label.pack(pady=5)
  207.         self.nome_entry = ttk.Entry(self, width=50)  # Aumentado
  208.         self.nome_entry.pack(pady=5)
  209.  
  210.         self.genero_label = ttk.Label(self, text="Gênero:")
  211.         self.genero_label.pack(pady=5)
  212.         self.genero_entry = ttk.Entry(self, width=50)  # Aumentado
  213.         self.genero_entry.pack(pady=5)
  214.  
  215.         self.url_label = ttk.Label(self, text="URL:")
  216.         self.url_label.pack(pady=5)
  217.         self.url_entry = ttk.Entry(self, width=50)  # Aumentado
  218.         self.url_entry.pack(pady=5)
  219.  
  220.         self.data_label = ttk.Label(self, text="Data:")
  221.         self.data_label.pack(pady=5)
  222.         self.data_entry = DateEntry(self, date_pattern='dd/mm/yyyy')
  223.         self.data_entry.pack(pady=5)
  224.  
  225.         self.save_button = ttk.Button(self, text="Salvar", command=self.save_entry)
  226.         self.save_button.pack(pady=20)
  227.  
  228.     def center_window(self):
  229.         self.update_idletasks()
  230.         width = self.winfo_width()
  231.         height = self.winfo_height()
  232.         x = (self.winfo_screenwidth() - width) // 2
  233.         y = (self.winfo_screenheight() - height) // 2
  234.         self.geometry(f'{width}x{height}+{x}+{y}')
  235.  
  236.     def save_entry(self):
  237.         nome = self.nome_entry.get().strip()
  238.         genero = self.genero_entry.get().strip()
  239.         url = self.url_entry.get().strip()
  240.         data = self.data_entry.get()
  241.         if nome and genero and url and data:
  242.             self.master.cursor.execute("INSERT INTO filmes (nome, genero, url, data) VALUES (?, ?, ?, ?)",
  243.                                        (nome, genero, url, data))
  244.             self.master.conn.commit()
  245.             self.master.refresh_tree()
  246.             self.destroy()
  247.         else:
  248.             messagebox.showerror("Erro", "Todos os campos devem ser preenchidos.")
  249.  
  250.  
  251. class EditEntryWindow(AddEntryWindow):
  252.     def __init__(self, parent, values):
  253.         super().__init__(parent)
  254.         self.values = values
  255.         self.fill_fields()
  256.  
  257.     def fill_fields(self):
  258.         self.nome_entry.insert(0, self.values[0])
  259.         self.genero_entry.insert(0, self.values[1])
  260.         self.url_entry.insert(0, self.values[2])
  261.         self.data_entry.set_date(self.values[3])
  262.  
  263.     def save_entry(self):
  264.         nome = self.nome_entry.get().strip()
  265.         genero = self.genero_entry.get().strip()
  266.         url = self.url_entry.get().strip()
  267.         data = self.data_entry.get()
  268.         if nome and genero and url and data:
  269.             selected_item = self.master.tree.selection()[0]
  270.             self.master.cursor.execute("""
  271.                UPDATE filmes
  272.                SET nome = ?, genero = ?, url = ?, data = ?
  273.                WHERE nome = ?
  274.            """, (nome, genero, url, data, self.values[0]))
  275.             self.master.conn.commit()
  276.             self.master.refresh_tree()
  277.             self.destroy()
  278.         else:
  279.             messagebox.showerror("Erro", "Todos os campos devem ser preenchidos.")
  280.  
  281.  
  282. if __name__ == "__main__":
  283.     app = Application()
  284.     app.mainloop()
  285.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement