The main theme I am going for is a dark theme with orange and light blue accents, and clean UI like much improved buttons. The following is code for an autoclicker. Your task is to optimize and beautify the front end (the main window that users see) so that it looks more professional. You may complete this task in any way, just know that it needs to run as a VSCode python file to start, and no administrator permissions are allowed. Here is the original code: import tkinter as tk
from tkinter import ttk, messagebox
import pyautogui
import time
import threading
import keyboard # External library: pip install keyboard
--- Configuration (Defaults) ---
DEFAULT_START_STOP_HOTKEY = "f6"
Key to press after clicking "Pick Location" button and moving mouse
DEFAULT_PICK_LOCATION_CAPTURE_KEY = "f7"
class AutoClickerApp:
def init(self, root):
self.root = root
root.title("Advanced Auto Clicker")
root.geometry("480x520") # Adjust size as needed, or let it auto-size
root.resizable(False, False)
Generated code
self.is_clicking = False
self.click_thread = None
self.clicks_done = 0
self.current_start_stop_hotkey = DEFAULT_START_STOP_HOTKEY
self.is_listening_for_pick_key = False
# Target coordinates for fixed position clicking
self.fixed_target_x = None
self.fixed_target_y = None
# --- Main Frame ---
main_frame = ttk.Frame(root, padding="10")
main_frame.grid(row=0, column=0, sticky="nsew")
root.grid_columnconfigure(0, weight=1) # Allow main_frame to expand
root.grid_rowconfigure(0, weight=1)
# --- Interval Frame ---
interval_frame = ttk.LabelFrame(main_frame, text="Click Interval")
interval_frame.grid(row=0, column=0, columnspan=2, padx=5, pady=5, sticky="ew")
ttk.Label(interval_frame, text="H:").grid(row=0, column=0, padx=(5,0), pady=5)
self.hr_var = tk.StringVar(value="0")
self.hr_entry = ttk.Entry(interval_frame, textvariable=self.hr_var, width=3)
self.hr_entry.grid(row=0, column=1, padx=(0,5), pady=5)
ttk.Label(interval_frame, text="M:").grid(row=0, column=2, padx=(5,0), pady=5)
self.min_var = tk.StringVar(value="0")
self.min_entry = ttk.Entry(interval_frame, textvariable=self.min_var, width=3)
self.min_entry.grid(row=0, column=3, padx=(0,5), pady=5)
ttk.Label(interval_frame, text="S:").grid(row=0, column=4, padx=(5,0), pady=5)
self.sec_var = tk.StringVar(value="3")
self.sec_entry = ttk.Entry(interval_frame, textvariable=self.sec_var, width=3)
self.sec_entry.grid(row=0, column=5, padx=(0,5), pady=5)
ttk.Label(interval_frame, text="MS:").grid(row=0, column=6, padx=(5,0), pady=5)
self.ms_var = tk.StringVar(value="0")
self.ms_entry = ttk.Entry(interval_frame, textvariable=self.ms_var, width=4)
self.ms_entry.grid(row=0, column=7, padx=(0,5), pady=5)
# --- Repeat Options Frame ---
repeat_frame = ttk.LabelFrame(main_frame, text="Repeat Options")
repeat_frame.grid(row=1, column=0, columnspan=2, padx=5, pady=5, sticky="ew")
self.repeat_mode_var = tk.StringVar(value="indefinite")
self.radio_indefinite = ttk.Radiobutton(repeat_frame, text="Repeat until stopped", variable=self.repeat_mode_var, value="indefinite", command=self._update_ui_states)
self.radio_indefinite.grid(row=0, column=0, padx=5, pady=2, sticky="w")
self.radio_fixed_repeat = ttk.Radiobutton(repeat_frame, text="Repeat", variable=self.repeat_mode_var, value="fixed", command=self._update_ui_states)
self.radio_fixed_repeat.grid(row=1, column=0, padx=5, pady=2, sticky="w")
self.num_clicks_var = tk.StringVar(value="10")
self.num_clicks_entry = ttk.Entry(repeat_frame, textvariable=self.num_clicks_var, width=7)
self.num_clicks_entry.grid(row=1, column=1, padx=5, pady=2, sticky="w")
ttk.Label(repeat_frame, text="times").grid(row=1, column=2, padx=5, pady=2, sticky="w")
# --- Cursor Position Frame ---
cursor_frame = ttk.LabelFrame(main_frame, text="Cursor Position")
cursor_frame.grid(row=2, column=0, columnspan=2, padx=5, pady=5, sticky="ew")
self.cursor_pos_mode_var = tk.StringVar(value="current")
self.radio_current_pos = ttk.Radiobutton(cursor_frame, text="Current mouse position", variable=self.cursor_pos_mode_var, value="current", command=self._update_ui_states)
self.radio_current_pos.grid(row=0, column=0, columnspan=3, padx=5, pady=2, sticky="w")
self.radio_fixed_pos = ttk.Radiobutton(cursor_frame, text="Fixed position:", variable=self.cursor_pos_mode_var, value="fixed", command=self._update_ui_states)
self.radio_fixed_pos.grid(row=1, column=0, padx=5, pady=2, sticky="w")
self.target_x_var = tk.StringVar(value="")
self.target_y_var = tk.StringVar(value="")
ttk.Label(cursor_frame, text="X:").grid(row=1, column=1, pady=2, sticky="e")
self.target_x_entry = ttk.Entry(cursor_frame, textvariable=self.target_x_var, width=5)
self.target_x_entry.grid(row=1, column=2, padx=(0,5), pady=2)
ttk.Label(cursor_frame, text="Y:").grid(row=1, column=3, pady=2, sticky="e")
self.target_y_entry = ttk.Entry(cursor_frame, textvariable=self.target_y_var, width=5)
self.target_y_entry.grid(row=1, column=4, padx=(0,5), pady=2)
self.pick_location_button_text = f"Pick (Press {DEFAULT_PICK_LOCATION_CAPTURE_KEY})"
self.pick_location_button = ttk.Button(cursor_frame, text=self.pick_location_button_text, command=self.initiate_pick_location)
self.pick_location_button.grid(row=1, column=5, padx=5, pady=2)
# --- Click Options Frame ---
click_options_frame = ttk.LabelFrame(main_frame, text="Click Options")
click_options_frame.grid(row=3, column=0, columnspan=2, padx=5, pady=5, sticky="ew")
ttk.Label(click_options_frame, text="Button:").grid(row=0, column=0, padx=5, pady=5, sticky="w")
self.mouse_button_var = tk.StringVar(value="left")
self.mouse_button_combo = ttk.Combobox(click_options_frame, textvariable=self.mouse_button_var, values=["left", "right", "middle"], width=8, state="readonly")
self.mouse_button_combo.grid(row=0, column=1, padx=5, pady=5)
ttk.Label(click_options_frame, text="Type:").grid(row=0, column=2, padx=5, pady=5, sticky="w")
self.click_type_var = tk.StringVar(value="single")
self.click_type_combo = ttk.Combobox(click_options_frame, textvariable=self.click_type_var, values=["single", "double"], width=8, state="readonly")
self.click_type_combo.grid(row=0, column=3, padx=5, pady=5)
# --- Hotkey Frame ---
hotkey_frame = ttk.LabelFrame(main_frame, text="Start/Stop Hotkey")
hotkey_frame.grid(row=4, column=0, columnspan=2, padx=5, pady=5, sticky="ew")
self.hotkey_var = tk.StringVar(value=DEFAULT_START_STOP_HOTKEY)
self.hotkey_entry = ttk.Entry(hotkey_frame, textvariable=self.hotkey_var, width=15)
self.hotkey_entry.grid(row=0, column=0, padx=5, pady=5)
self.set_hotkey_button = ttk.Button(hotkey_frame, text="Set Hotkey", command=self.set_new_start_stop_hotkey)
self.set_hotkey_button.grid(row=0, column=1, padx=5, pady=5)
# --- Control Buttons ---
self.start_button = ttk.Button(main_frame, command=self.start_clicking) # Text set in _update_ui_states
self.start_button.grid(row=5, column=0, padx=5, pady=10, sticky="ew")
self.stop_button = ttk.Button(main_frame, command=self.stop_clicking) # Text set in _update_ui_states
self.stop_button.grid(row=5, column=1, padx=5, pady=10, sticky="ew")
# --- Status Bar ---
self.status_var = tk.StringVar(value="Status: Idle")
status_label = ttk.Label(main_frame, textvariable=self.status_var, relief=tk.SUNKEN, anchor="w")
status_label.grid(row=6, column=0, columnspan=2, padx=5, pady=(5,0), sticky="ew")
self.all_input_elements = [
self.hr_entry, self.min_entry, self.sec_entry, self.ms_entry,
self.radio_indefinite, self.radio_fixed_repeat, self.num_clicks_entry,
self.radio_current_pos, self.radio_fixed_pos, self.target_x_entry, self.target_y_entry,
self.pick_location_button,
self.mouse_button_combo, self.click_type_combo,
self.hotkey_entry, self.set_hotkey_button
]
self._update_ui_states() # Initial setup of UI element states
self._setup_start_stop_hotkey() # Initial hotkey registration
root.protocol("WM_DELETE_WINDOW", self.on_closing)
def _update_ui_states(self):
is_idle_and_not_picking = not self.is_clicking and not self.is_listening_for_pick_key
# Enable/disable all input elements based on main state
for elem in self.all_input_elements:
elem.config(state="normal" if is_idle_and_not_picking else "disabled")
# Specific states for dependent entries
if is_idle_and_not_picking:
self.num_clicks_entry.config(state="normal" if self.repeat_mode_var.get() == "fixed" else "disabled")
is_fixed_pos_mode = self.cursor_pos_mode_var.get() == "fixed"
self.target_x_entry.config(state="normal" if is_fixed_pos_mode else "disabled")
self.target_y_entry.config(state="normal" if is_fixed_pos_mode else "disabled")
self.pick_location_button.config(state="normal" if is_fixed_pos_mode else "disabled")
else: # If clicking or picking, all these are disabled
self.num_clicks_entry.config(state="disabled")
self.target_x_entry.config(state="disabled")
self.target_y_entry.config(state="disabled")
self.pick_location_button.config(state="disabled")
# Start/Stop buttons
hotkey_display = f" ({self.current_start_stop_hotkey})" if self.current_start_stop_hotkey else ""
self.start_button.config(text=f"Start{hotkey_display}", state="normal" if is_idle_and_not_picking else "disabled")
self.stop_button.config(text=f"Stop{hotkey_display}", state="disabled" if is_idle_and_not_picking else "normal")
if self.is_clicking : # Override if clicking
self.start_button.config(state="disabled")
self.stop_button.config(state="normal")
def _update_status(self, message):
self.status_var.set(f"Status: {message}")
def get_total_interval_seconds(self):
try:
h = int(self.hr_var.get() or "0")
m = int(self.min_var.get() or "0")
s = int(self.sec_var.get() or "0")
ms = int(self.ms_var.get() or "0")
if any(x < 0 for x in [h, m, s, ms]):
raise ValueError("Time components cannot be negative.")
total_seconds = h * 3600 + m * 60 + s + ms / 1000.0
if total_seconds < 0.01 and total_seconds > 0: # pyautogui min sleep is around 0.01
messagebox.showwarning("Low Interval", "Interval is very low. PyAutoGUI has practical limits.")
elif total_seconds <= 0:
messagebox.showerror("Invalid Interval", "Total click interval must be greater than 0.")
return None
return total_seconds
except ValueError as e:
messagebox.showerror("Invalid Interval Input", f"Please enter valid numbers for interval. Error: {e}")
return None
def _validate_all_inputs(self):
interval = self.get_total_interval_seconds()
if interval is None: return None
params = {'interval': interval}
params['repeat_count'] = None
if self.repeat_mode_var.get() == "fixed":
try:
params['repeat_count'] = int(self.num_clicks_var.get())
if params['repeat_count'] <= 0:
messagebox.showerror("Invalid Input", "Number of clicks must be a positive integer.")
return None
except ValueError:
messagebox.showerror("Invalid Input", "Number of clicks must be an integer.")
return None
params['click_button'] = self.mouse_button_var.get()
params['click_type'] = self.click_type_var.get()
params['target_x'], params['target_y'] = None, None
if self.cursor_pos_mode_var.get() == "fixed":
try:
params['target_x'] = int(self.target_x_var.get())
params['target_y'] = int(self.target_y_var.get())
except ValueError:
messagebox.showerror("Invalid Position", "Fixed X and Y coordinates must be integers.")
return None
return params
def set_new_start_stop_hotkey(self):
if self.is_clicking or self.is_listening_for_pick_key:
messagebox.showwarning("Busy", "Cannot change hotkey while auto-clicker is active or picking location.")
return
new_hotkey = self.hotkey_var.get().strip().lower()
if not new_hotkey:
messagebox.showwarning("Hotkey Error", "Hotkey cannot be empty.")
return
if self.current_start_stop_hotkey: # Unregister old hotkey
try: keyboard.remove_hotkey(self.current_start_stop_hotkey)
except Exception: pass # May fail if not registered or already removed
self.current_start_stop_hotkey = new_hotkey
self._setup_start_stop_hotkey()
self._update_ui_states() # Update button texts
def _setup_start_stop_hotkey(self):
if self.current_start_stop_hotkey:
try:
keyboard.add_hotkey(self.current_start_stop_hotkey, self._toggle_clicking_via_hotkey, suppress=False)
self._update_status(f"Idle. Hotkey: {self.current_start_stop_hotkey}")
except Exception as e:
messagebox.showerror("Hotkey Error", f"Failed to set hotkey '{self.current_start_stop_hotkey}': {e}\nConsider simpler hotkeys (e.g., 'f6', 'ctrl+alt+k').")
self.current_start_stop_hotkey = "" # Clear invalid hotkey
self._update_status("Idle. Hotkey registration failed.")
else: # No hotkey
self._update_status("Idle. No hotkey set.")
def _toggle_clicking_via_hotkey(self):
if self.is_listening_for_pick_key: return # Don't interfere
if self.is_clicking:
self.stop_clicking()
else:
self.start_clicking()
def initiate_pick_location(self):
if self.is_clicking or self.is_listening_for_pick_key: return
self.is_listening_for_pick_key = True
self._update_ui_states() # Disable most UI
self._update_status(f"Picking: Move mouse & press '{DEFAULT_PICK_LOCATION_CAPTURE_KEY}' to capture position.")
try:
keyboard.add_hotkey(DEFAULT_PICK_LOCATION_CAPTURE_KEY, self._capture_location_on_key, suppress=True)
except Exception as e:
messagebox.showerror("Error", f"Could not set up location capture hotkey ({DEFAULT_PICK_LOCATION_CAPTURE_KEY}): {e}")
self._finish_pick_location(success=False)
def _capture_location_on_key(self):
if not self.is_listening_for_pick_key: return
try:
keyboard.remove_hotkey(DEFAULT_PICK_LOCATION_CAPTURE_KEY) # One-shot
except Exception: pass
self.fixed_target_x, self.fixed_target_y = pyautogui.position()
self.target_x_var.set(str(self.fixed_target_x))
self.target_y_var.set(str(self.fixed_target_y))
self._finish_pick_location(success=True)
def _finish_pick_location(self, success=True):
self.is_listening_for_pick_key = False
self._update_ui_states() # Re-enable UI
if success:
self._update_status(f"Location set: ({self.fixed_target_x}, {self.fixed_target_y}). Ready.")
else:
self._update_status("Location picking cancelled or failed. Ready.")
def start_clicking(self):
if self.is_clicking or self.is_listening_for_pick_key: return
click_params = self._validate_all_inputs()
if not click_params: return
self.is_clicking = True
self.clicks_done = 0
self._update_ui_states() # Disables inputs, updates button states
self._update_status("Clicking...")
self.click_thread = threading.Thread(target=self._click_loop, args=(click_params,), daemon=True)
self.click_thread.start()
def stop_clicking(self, reason="Stopped by user"):
if not self.is_clicking: return
self.is_clicking = False # Signal thread to stop
# Thread is daemon, will exit. No forceful join to keep GUI responsive.
self._update_ui_states() # Re-enables inputs
self._update_status(reason)
def _click_loop(self, params):
try:
while self.is_clicking:
current_x, current_y = pyautogui.position() # Default to current
if self.cursor_pos_mode_var.get() == "fixed" and params['target_x'] is not None:
current_x, current_y = params['target_x'], params['target_y']
# Perform click
if params['click_type'] == "single":
pyautogui.click(x=current_x, y=current_y, button=params['click_button'])
elif params['click_type'] == "double":
pyautogui.doubleClick(x=current_x, y=current_y, button=params['click_button'])
self.clicks_done += 1
status_msg_parts = [f"Clicked {self.clicks_done} times"]
if params['repeat_count']:
status_msg_parts.append(f"/ {params['repeat_count']}")
self.root.after(0, self._update_status, " ".join(status_msg_parts)) # GUI update from main thread
if params['repeat_count'] and self.clicks_done >= params['repeat_count']:
self.root.after(0, self.stop_clicking, f"Finished {params['repeat_count']} clicks.")
break
if not self.is_clicking: break
time.sleep(params['interval'])
except pyautogui.FailSafeException:
self.root.after(0, self.stop_clicking, "Fail-safe triggered (mouse to top-left)!")
except Exception as e:
error_msg = f"Runtime Error: {e}"
print(error_msg) # Log to console for debugging
self.root.after(0, messagebox.showerror, "Clicking Error", error_msg)
self.root.after(0, self.stop_clicking, "Error occurred during clicking.")
finally:
# If loop terminated unexpectedly while is_clicking was still true
if self.is_clicking:
self.root.after(0, self.stop_clicking, "Clicking loop terminated unexpectedly.")
def on_closing(self):
if self.is_clicking:
if not messagebox.askokcancel("Quit", "Auto-clicker is active. Stop and quit?"):
return # User cancelled quit
self.stop_clicking("Exiting application.")
# Clean up all hotkeys
if self.current_start_stop_hotkey:
try: keyboard.remove_hotkey(self.current_start_stop_hotkey)
except: pass
if self.is_listening_for_pick_key: # Should be false, but just in case
try: keyboard.remove_hotkey(DEFAULT_PICK_LOCATION_CAPTURE_KEY)
except: pass
# A more robust way if many dynamic hotkeys: keyboard.unhook_all_hotkeys()
# For this app, specific removal is fine.
self.root.destroy()
if name == "main":
try:
main_root = tk.Tk()
app = AutoClickerApp(main_root)
main_root.mainloop()
except ImportError:
print("Required libraries not found. Please install them:")
print("pip install pyautogui keyboard")
except Exception as e:
print(f"An error occurred on startup: {e}")
print("This might be due to permissions required by the 'keyboard' library.")
print("- On Linux, try running with 'sudo'.")
print("- On macOS, ensure your Terminal/IDE has Accessibility permissions.")
print("- On Windows, try running as Administrator if you encounter issues.")