Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import tkinter as tk
- from tkinter import filedialog, messagebox, Label, Scrollbar, simpledialog
- from PIL import Image, ImageTk
- import sqlite3
- import io
- # Set a predefined password
- DATABASE_PASSWORD = "1234"
- # Prompt for a password before proceeding
- def authenticate():
- password = simpledialog.askstring("Password", "Enter database password:", show="*")
- if password != DATABASE_PASSWORD:
- messagebox.showerror("Error", "Incorrect password!")
- root.destroy() # Close the application if the password is incorrect
- # Connect to the SQLite database and create the table
- def connect_db():
- conn = sqlite3.connect("ImagesData.db")
- cursor = conn.cursor()
- cursor.execute("""
- CREATE TABLE IF NOT EXISTS images (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- name TEXT UNIQUE,
- image BLOB
- )
- """)
- conn.commit()
- conn.close()
- # Add a new image to the database
- def add_image():
- name = name_entry.get().strip()
- file_path = filedialog.askopenfilename(title="Select Image", filetypes=[("Image files", "*.png;*.jpg;*.jpeg;*.bmp")])
- if name and file_path:
- try:
- with open(file_path, "rb") as file:
- image_data = file.read()
- conn = sqlite3.connect("ImagesData.db")
- cursor = conn.cursor()
- cursor.execute("INSERT INTO images (name, image) VALUES (?, ?)", (name, image_data))
- conn.commit()
- conn.close()
- messagebox.showinfo("Success", "Image added successfully!")
- name_entry.delete(0, tk.END)
- show_all_images()
- except sqlite3.IntegrityError:
- messagebox.showerror("Error", "Image name already exists.")
- else:
- messagebox.showwarning("Input Error", "Please enter a name and select an image.")
- # Search for an image by name
- def search_image():
- name = search_entry.get().strip()
- if name:
- conn = sqlite3.connect("ImagesData.db")
- cursor = conn.cursor()
- cursor.execute("SELECT image FROM images WHERE name = ?", (name,))
- result = cursor.fetchone()
- conn.close()
- if result:
- show_image(result[0])
- else:
- messagebox.showinfo("Not Found", "Image not found.")
- else:
- messagebox.showwarning("Input Error", "Please enter an image name to search.")
- # Show all image names
- def show_all_images():
- conn = sqlite3.connect("ImagesData.db")
- cursor = conn.cursor()
- cursor.execute("SELECT name FROM images")
- results = cursor.fetchall()
- conn.close()
- image_list.delete(0, tk.END)
- for row in results:
- image_list.insert(tk.END, row[0])
- # Display the selected image
- def display_image_content(event):
- try:
- selected_name = image_list.get(image_list.curselection())
- conn = sqlite3.connect("ImagesData.db")
- cursor = conn.cursor()
- cursor.execute("SELECT image FROM images WHERE name = ?", (selected_name,))
- result = cursor.fetchone()
- conn.close()
- if result:
- show_image(result[0])
- except tk.TclError:
- pass # No item selected
- # Show image in label with fit-to-screen functionality
- def show_image(image_data):
- image = Image.open(io.BytesIO(image_data))
- image.thumbnail((600, 600)) # Resize to fit within 600x600 pixels
- photo = ImageTk.PhotoImage(image)
- image_label.config(image=photo)
- image_label.image = photo # Keep reference
- # Store the image data for saving
- global current_image_data
- current_image_data = image_data
- # Save the displayed image to a file
- def save_image():
- if current_image_data:
- save_path = filedialog.asksaveasfilename(defaultextension=".png",
- filetypes=[("PNG files", "*.png"), ("JPEG files", "*.jpg"), ("All files", "*.*")])
- if save_path:
- with open(save_path, "wb") as file:
- file.write(current_image_data)
- messagebox.showinfo("Saved", "Image saved successfully!")
- else:
- messagebox.showwarning("No Image", "No image loaded to save.")
- # Delete the selected image from the database
- def delete_image():
- if image_list.curselection():
- selected_name = image_list.get(image_list.curselection())
- confirm = messagebox.askyesno("Confirm Delete", f"Are you sure you want to delete '{selected_name}'?")
- if confirm:
- conn = sqlite3.connect("ImagesData.db")
- cursor = conn.cursor()
- cursor.execute("DELETE FROM images WHERE name = ?", (selected_name,))
- conn.commit()
- conn.close()
- messagebox.showinfo("Success", "Image deleted successfully!")
- show_all_images() # Refresh the image list
- image_label.config(image="") # Clear the image display
- else:
- messagebox.showwarning("Selection Error", "Please select an image first to delete.")
- # GUI Setup
- root = tk.Tk()
- root.title("Najeeb Image Database")
- root.geometry("900x640")
- root.configure(bg="#f0f0f5")
- # Authenticate first
- authenticate()
- connect_db()
- # Top Row: Search, Add, Show All in One Line
- style_label = {"bg": "#f0f0f5", "fg": "#333333", "font": ("Arial", 11)}
- style_button = {"bg": "#4CAF50", "fg": "white", "font": ("Arial", 10, "bold"), "width": 14, "padx": 2, "pady": 2}
- tk.Label(root, text="Search Image Name:", **style_label).grid(row=0, column=3, padx=5, pady=5, sticky="w")
- search_entry = tk.Entry(root, width=15, font=("Arial", 11))
- search_entry.grid(row=0, column=4, padx=5, pady=5, sticky="w")
- search_button = tk.Button(root, text="Search", command=search_image, **style_button)
- search_button.grid(row=0, column=5, padx=5, pady=5, sticky="w")
- tk.Label(root, text="Add New Image:", **style_label).grid(row=0, column=0, padx=5, pady=5, sticky="w")
- name_entry = tk.Entry(root, width=15, font=("Arial", 11))
- name_entry.grid(row=0, column=1, padx=5, pady=5, sticky="w")
- add_button = tk.Button(root, text="Add Image", command=add_image, **style_button)
- add_button.grid(row=0, column=2, padx=5, pady=5, sticky="w")
- show_all_button = tk.Button(root, text="Show All Images", command=show_all_images, **style_button)
- show_all_button.grid(row=1, column=0, padx=5, pady=5, sticky="w")
- # Delete and Save Buttons
- delete_button = tk.Button(root, text="Delete", command=delete_image, **style_button)
- delete_button.grid(row=1, column=1, padx=5, pady=5, sticky="w")
- save_button = tk.Button(root, text="Save Image", command=save_image, **style_button)
- save_button.grid(row=1, column=2, padx=5, pady=5, sticky="w")
- # Image List
- list_frame = tk.Frame(root)
- list_frame.grid(row=2, column=0, rowspan=6, padx=5, pady=5, sticky="n")
- image_list = tk.Listbox(list_frame, width=20, height=29, font=("Arial", 11))
- image_list.pack(side="left", fill="y")
- scrollbar = Scrollbar(list_frame, orient="vertical", command=image_list.yview)
- scrollbar.pack(side="right", fill="y")
- image_list.config(yscrollcommand=scrollbar.set)
- image_list.bind("<<ListboxSelect>>", display_image_content)
- # Image Display Label
- image_frame = tk.Frame(root)
- image_frame.grid(row=2, column=1, rowspan=6, columnspan=5, padx=5, pady=5, sticky="n")
- image_label = Label(image_frame)
- image_label.pack()
- # Run main loop
- current_image_data = None # Variable to store image data for saving
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement