Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Tutorial: https://www.youtube.com/watch?v=OatbzMJIfJM
- # pip install requests Pillow openai
- import tkinter as tk
- from tkinter import filedialog, ttk, messagebox, Canvas, Scrollbar
- from openai import OpenAI
- import threading
- import requests
- from PIL import Image, ImageTk
- import io
- import os
- import uuid
- # Save the API key securely
- def save_api_key():
- with open('api_key.txt', 'w') as file:
- file.write(api_key_entry.get())
- # Load the API key securely
- def load_api_key():
- try:
- with open('api_key.txt', 'r') as file:
- api_key_entry.insert(0, file.read())
- except FileNotFoundError:
- messagebox.showerror("Error", "API Key file not found.")
- # Function to generate and display image(s)
- def generate_image_thread():
- threading.Thread(target=generate_image).start()
- def generate_image():
- clear_image_grid() # Added line to clear the image grid
- status_label.config(text="Running")
- client = OpenAI(api_key=api_key_entry.get())
- prompt = prompt_entry.get("1.0", tk.END).strip()
- size = size_var.get()
- quality = quality_var.get()
- num_images = int(num_images_var.get())
- progress_bar['maximum'] = num_images
- progress_bar['value'] = 0
- try:
- image_counter = 0
- for _ in range(num_images):
- response = client.images.generate(
- model="dall-e-3",
- prompt=prompt,
- size=size,
- quality=quality,
- n=1,
- )
- img_url = response.data[0].url
- img_response = requests.get(img_url)
- img = Image.open(io.BytesIO(img_response.content))
- display_img = img.copy()
- display_img.thumbnail((400, 400)) # Resize for display
- tk_img = ImageTk.PhotoImage(display_img)
- image_label = tk.Label(image_frame, image=tk_img)
- image_label.image = tk_img
- image_label.grid(row=0, column=image_counter, padx=5, pady=5)
- image_counter += 1
- filename = f'{uuid.uuid4()}.png'
- img.save(os.path.join(save_folder.get(), filename))
- progress_bar['value'] += 1
- root.update_idletasks()
- except Exception as e:
- messagebox.showerror("Error", f"An error occurred: {e}")
- status_label.config(text="Idle")
- # Function to select save folder
- def select_save_folder():
- folder_selected = filedialog.askdirectory()
- save_folder.set(folder_selected if folder_selected else save_folder.get())
- # Function to clear image grid
- def clear_image_grid():
- for widget in image_frame.winfo_children():
- widget.destroy()
- # Custom style improvements
- def apply_custom_style(root):
- style = ttk.Style(root)
- style.theme_use('clam')
- # Customizing general widget styles
- style.configure('TLabel', background='#333333', foreground='#DDDDDD', font=('Arial', 14, 'bold'))
- style.configure('TEntry', fieldbackground='#555555', foreground='#EEEEEE', font=('Arial', 14, 'bold'))
- style.configure('TButton', background='#444444', foreground='#FFFFFF', font=('Arial', 14, 'bold'), borderwidth=1)
- style.configure('TCheckbutton', background='#333333', foreground='#FFFFFF', font=('Arial', 14, 'bold'))
- style.configure('TFrame', background='#333333')
- style.configure('Horizontal.TProgressbar', background='#5AA33F', troughcolor='#333333')
- style.configure('TCombobox', font=('Arial', 12)) # Adjusting font size for dropdown menus
- # Customizing specific widget styles
- style.map('TButton', background=[('active', '#555555')], foreground=[('active', '#FFFFFF')])
- return style
- # Horizontal Scrollable Image Frame
- def create_scrollable_image_frame(root):
- canvas = Canvas(root, bg="#333333")
- scrollbar = Scrollbar(root, orient="horizontal", command=canvas.xview)
- scrollable_frame = ttk.Frame(canvas)
- scrollable_frame.bind(
- "<Configure>",
- lambda e: canvas.configure(
- scrollregion=canvas.bbox("all")
- )
- )
- canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
- canvas.configure(xscrollcommand=scrollbar.set)
- canvas.pack(side="top", fill="both", expand=True)
- scrollbar.pack(side="bottom", fill="x")
- return scrollable_frame
- # Create the main window
- root = tk.Tk()
- root.title("dall-e-desktop-ui")
- root.geometry('800x800') # Set initial size
- root.config(bg="#333333")
- apply_custom_style(root) # Apply custom styles
- # Variables for UI elements
- size_var = tk.StringVar(value="1024x1024")
- quality_var = tk.StringVar(value="standard")
- num_images_var = tk.StringVar(value="1")
- save_folder = tk.StringVar(value=os.path.expanduser("~"))
- # API Key UI
- api_key_label = ttk.Label(root, text="API Key:")
- api_key_label.pack(pady=(10, 0))
- api_key_entry = ttk.Entry(root)
- api_key_entry.pack(padx=10, pady=5)
- save_api_button = ttk.Button(root, text="Save API Key", command=save_api_key)
- save_api_button.pack(pady=5)
- # Dropdowns for Size, Quality, and Number of Images
- settings_frame = ttk.Frame(root)
- settings_frame.pack(padx=10, pady=10, fill='x')
- ttk.Label(settings_frame, text="Image Size:").pack(side='left')
- ttk.Combobox(settings_frame, textvariable=size_var, values=["1024x1024", "1024x1792", "1792x1024"]).pack(side='left')
- ttk.Label(settings_frame, text="Image Quality:").pack(side='left')
- ttk.Combobox(settings_frame, textvariable=quality_var, values=["standard", "hd"]).pack(side='left')
- ttk.Label(settings_frame, text="Number of Images:").pack(side='left')
- ttk.Combobox(settings_frame, textvariable=num_images_var, values=[str(x) for x in range(1, 11)]).pack(side='left')
- # Prompt Text Area
- prompt_label = ttk.Label(root, text="Prompt:")
- prompt_label.pack(pady=(10, 0))
- prompt_entry = tk.Text(root, height=4)
- prompt_entry.pack(fill='both', expand=True, padx=10, pady=5)
- # Save Folder UI
- save_folder_frame = ttk.Frame(root)
- save_folder_frame.pack(padx=10, pady=10, fill='x')
- ttk.Label(save_folder_frame, text="Save Images to:").pack(side='left')
- save_folder_entry = ttk.Entry(save_folder_frame, textvariable=save_folder)
- save_folder_entry.pack(side='left', fill='x', expand=True)
- select_folder_button = ttk.Button(save_folder_frame, text="Select Folder", command=select_save_folder)
- select_folder_button.pack(side='left')
- # Generate Image Button and Progress Bar
- generate_button = ttk.Button(root, text="Generate Image", command=generate_image_thread)
- generate_button.pack(pady=5)
- progress_bar = ttk.Progressbar(root, orient='horizontal', length=200, mode='determinate', style='Horizontal.TProgressbar')
- progress_bar.pack(pady=(5, 10))
- # Image Display Frame
- image_frame = create_scrollable_image_frame(root)
- # Status Label
- status_label = ttk.Label(root, text="Idle")
- status_label.pack(pady=(5, 10))
- # Load the API key if it exists
- load_api_key()
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement