SHARE
    TWEET
    Najeebsk

    PICTURES-DATA.pyw

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

    AltStyle によって変換されたページ (->オリジナル) /