Advertisement
Najeebsk

PICTURES-DATA.pyw

Oct 29th, 2024
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.34 KB | None | 0 0
  1. import tkinter as tk
  2. from tkinter import filedialog, messagebox, Label, Scrollbar, simpledialog
  3. from PIL import Image, ImageTk
  4. import sqlite3
  5. import io
  6.  
  7. # Set a predefined password
  8. DATABASE_PASSWORD = "1234"
  9.  
  10. # Prompt for a password before proceeding
  11. def authenticate():
  12.     password = simpledialog.askstring("Password", "Enter database password:", show="*")
  13.     if password != DATABASE_PASSWORD:
  14.         messagebox.showerror("Error", "Incorrect password!")
  15.         root.destroy()  # Close the application if the password is incorrect
  16.  
  17. # Connect to the SQLite database and create the table
  18. def connect_db():
  19.     conn = sqlite3.connect("ImagesData.db")
  20.     cursor = conn.cursor()
  21.     cursor.execute("""
  22.    CREATE TABLE IF NOT EXISTS images (
  23.        id INTEGER PRIMARY KEY AUTOINCREMENT,
  24.        name TEXT UNIQUE,
  25.        image BLOB
  26.    )
  27.    """)
  28.     conn.commit()
  29.     conn.close()
  30.  
  31. # Add a new image to the database
  32. def add_image():
  33.     name = name_entry.get().strip()
  34.     file_path = filedialog.askopenfilename(title="Select Image", filetypes=[("Image files", "*.png;*.jpg;*.jpeg;*.bmp")])
  35.    
  36.     if name and file_path:
  37.         try:
  38.             with open(file_path, "rb") as file:
  39.                 image_data = file.read()
  40.             conn = sqlite3.connect("ImagesData.db")
  41.             cursor = conn.cursor()
  42.             cursor.execute("INSERT INTO images (name, image) VALUES (?, ?)", (name, image_data))
  43.             conn.commit()
  44.             conn.close()
  45.             messagebox.showinfo("Success", "Image added successfully!")
  46.             name_entry.delete(0, tk.END)
  47.             show_all_images()
  48.         except sqlite3.IntegrityError:
  49.             messagebox.showerror("Error", "Image name already exists.")
  50.     else:
  51.         messagebox.showwarning("Input Error", "Please enter a name and select an image.")
  52.  
  53. # Search for an image by name
  54. def search_image():
  55.     name = search_entry.get().strip()
  56.     if name:
  57.         conn = sqlite3.connect("ImagesData.db")
  58.         cursor = conn.cursor()
  59.         cursor.execute("SELECT image FROM images WHERE name = ?", (name,))
  60.         result = cursor.fetchone()
  61.         conn.close()
  62.         if result:
  63.             show_image(result[0])
  64.         else:
  65.             messagebox.showinfo("Not Found", "Image not found.")
  66.     else:
  67.         messagebox.showwarning("Input Error", "Please enter an image name to search.")
  68.  
  69. # Show all image names
  70. def show_all_images():
  71.     conn = sqlite3.connect("ImagesData.db")
  72.     cursor = conn.cursor()
  73.     cursor.execute("SELECT name FROM images")
  74.     results = cursor.fetchall()
  75.     conn.close()
  76.     image_list.delete(0, tk.END)
  77.     for row in results:
  78.         image_list.insert(tk.END, row[0])
  79.  
  80. # Display the selected image
  81. def display_image_content(event):
  82.     try:
  83.         selected_name = image_list.get(image_list.curselection())
  84.         conn = sqlite3.connect("ImagesData.db")
  85.         cursor = conn.cursor()
  86.         cursor.execute("SELECT image FROM images WHERE name = ?", (selected_name,))
  87.         result = cursor.fetchone()
  88.         conn.close()
  89.         if result:
  90.             show_image(result[0])
  91.     except tk.TclError:
  92.         pass  # No item selected
  93.  
  94. # Show image in label with fit-to-screen functionality
  95. def show_image(image_data):
  96.     image = Image.open(io.BytesIO(image_data))
  97.     image.thumbnail((600, 600))  # Resize to fit within 600x600 pixels
  98.     photo = ImageTk.PhotoImage(image)
  99.     image_label.config(image=photo)
  100.     image_label.image = photo  # Keep reference
  101.     # Store the image data for saving
  102.     global current_image_data
  103.     current_image_data = image_data
  104.  
  105. # Save the displayed image to a file
  106. def save_image():
  107.     if current_image_data:
  108.         save_path = filedialog.asksaveasfilename(defaultextension=".png",
  109.                                                  filetypes=[("PNG files", "*.png"), ("JPEG files", "*.jpg"), ("All files", "*.*")])
  110.         if save_path:
  111.             with open(save_path, "wb") as file:
  112.                 file.write(current_image_data)
  113.             messagebox.showinfo("Saved", "Image saved successfully!")
  114.     else:
  115.         messagebox.showwarning("No Image", "No image loaded to save.")
  116.  
  117. # Delete the selected image from the database
  118. def delete_image():
  119.     if image_list.curselection():
  120.         selected_name = image_list.get(image_list.curselection())
  121.         confirm = messagebox.askyesno("Confirm Delete", f"Are you sure you want to delete '{selected_name}'?")
  122.         if confirm:
  123.             conn = sqlite3.connect("ImagesData.db")
  124.             cursor = conn.cursor()
  125.             cursor.execute("DELETE FROM images WHERE name = ?", (selected_name,))
  126.             conn.commit()
  127.             conn.close()
  128.             messagebox.showinfo("Success", "Image deleted successfully!")
  129.             show_all_images()  # Refresh the image list
  130.             image_label.config(image="")  # Clear the image display
  131.     else:
  132.         messagebox.showwarning("Selection Error", "Please select an image first to delete.")
  133.  
  134. # GUI Setup
  135. root = tk.Tk()
  136. root.title("Najeeb Image Database")
  137. root.geometry("900x640")
  138. root.configure(bg="#f0f0f5")
  139.  
  140. # Authenticate first
  141. authenticate()
  142.  
  143. connect_db()
  144.  
  145. # Top Row: Search, Add, Show All in One Line
  146. style_label = {"bg": "#f0f0f5", "fg": "#333333", "font": ("Arial", 11)}
  147. style_button = {"bg": "#4CAF50", "fg": "white", "font": ("Arial", 10, "bold"), "width": 14, "padx": 2, "pady": 2}
  148.  
  149. tk.Label(root, text="Search Image Name:", **style_label).grid(row=0, column=3, padx=5, pady=5, sticky="w")
  150. search_entry = tk.Entry(root, width=15, font=("Arial", 11))
  151. search_entry.grid(row=0, column=4, padx=5, pady=5, sticky="w")
  152.  
  153. search_button = tk.Button(root, text="Search", command=search_image, **style_button)
  154. search_button.grid(row=0, column=5, padx=5, pady=5, sticky="w")
  155.  
  156. tk.Label(root, text="Add New Image:", **style_label).grid(row=0, column=0, padx=5, pady=5, sticky="w")
  157. name_entry = tk.Entry(root, width=15, font=("Arial", 11))
  158. name_entry.grid(row=0, column=1, padx=5, pady=5, sticky="w")
  159.  
  160. add_button = tk.Button(root, text="Add Image", command=add_image, **style_button)
  161. add_button.grid(row=0, column=2, padx=5, pady=5, sticky="w")
  162.  
  163. show_all_button = tk.Button(root, text="Show All Images", command=show_all_images, **style_button)
  164. show_all_button.grid(row=1, column=0, padx=5, pady=5, sticky="w")
  165.  
  166. # Delete and Save Buttons
  167. delete_button = tk.Button(root, text="Delete", command=delete_image, **style_button)
  168. delete_button.grid(row=1, column=1, padx=5, pady=5, sticky="w")
  169.  
  170. save_button = tk.Button(root, text="Save Image", command=save_image, **style_button)
  171. save_button.grid(row=1, column=2, padx=5, pady=5, sticky="w")
  172.  
  173. # Image List
  174. list_frame = tk.Frame(root)
  175. list_frame.grid(row=2, column=0, rowspan=6, padx=5, pady=5, sticky="n")
  176. image_list = tk.Listbox(list_frame, width=20, height=29, font=("Arial", 11))
  177. image_list.pack(side="left", fill="y")
  178. scrollbar = Scrollbar(list_frame, orient="vertical", command=image_list.yview)
  179. scrollbar.pack(side="right", fill="y")
  180. image_list.config(yscrollcommand=scrollbar.set)
  181. image_list.bind("<<ListboxSelect>>", display_image_content)
  182.  
  183. # Image Display Label
  184. image_frame = tk.Frame(root)
  185. image_frame.grid(row=2, column=1, rowspan=6, columnspan=5, padx=5, pady=5, sticky="n")
  186. image_label = Label(image_frame)
  187. image_label.pack()
  188.  
  189. # Run main loop
  190. current_image_data = None  # Variable to store image data for saving
  191. root.mainloop()
  192.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement