Build a Pro Random Color Generator with Python and Tkinter
Source: Dev.to
Random Color Generator Desktop App (Tkinter)
In this tutorial we’ll build a desktop app using Python’s tkinter that generates random colors and displays their HEX, RGB, and HSL values. The guide is broken down step‑by‑step so beginners can follow along.
Step 1 – Import Required Modules
import sys
import os
import tkinter as tk
from tkinter import messagebox
import random
import colorsys
Explanation
| Module | Purpose |
|---|---|
tkinter | Build the GUI |
messagebox | Show pop‑up messages (e.g., “Copied to clipboard”) |
random | Generate random colour values |
colorsys | Convert RGB values to HSL format |
Step 2 – Define the App Theme
# Colours
APP_BG = "#121212"
PANEL_BG = "#1F1F1F"
BTN_BG = "#2C2C2C"
ACCENT = "#FF6F61"
TEXT_CLR = "#E0E0E0"
SUBTEXT_CLR = "#AAAAAA"
INPUT_BG = "#333333"
INPUT_FG = "#FFFFFF"
# Font
FONT = ("Segoe UI", 11)
Explanation
- Consistent background, button, accent, and text colours give the app a modern dark theme.
FONTis applied to labels, buttons, and other text widgets.
Step 3 – Create the Main App Class
class RandomColorGeneratorApp:
def __init__(self, root):
self.root = root
root.title("MateTools – Pro Random Color Generator")
root.geometry("1000x620")
root.configure(bg=APP_BG)
root.resizable(False, False)
Explanation
root– the main Tkinter window.title()– sets the window title.geometry()– defines the window size.resizable(False, False)– disables resizing.
Step 4 – Build the Left Panel (Controls)
# Left panel container
left = tk.Frame(root, bg=PANEL_BG, width=420)
left.pack(side="left", fill="y")
# Header labels
tk.Label(
left,
text="MateTools",
bg=PANEL_BG,
fg=ACCENT,
font=("Segoe UI", 20, "bold")
).pack(padx=16, pady=(18, 10))
tk.Label(
left,
text="Pro Random Color Generator",
bg=PANEL_BG,
fg=TEXT_CLR,
font=("Segoe UI", 14, "bold")
).pack(anchor="w", padx=16, pady=(0, 2))
Explanation
Frame– a container for widgets.Label– displays static text.pack()– geometry manager;side="left"pins the panel to the left side.
Step 5 – Add Buttons
# Button container
btn_frame = tk.Frame(left, bg=PANEL_BG)
btn_frame.pack(fill="x", padx=16, pady=16)
def make_btn(text, cmd, color=BTN_BG):
"""Helper to create a styled button."""
return tk.Button(
btn_frame,
text=text,
command=cmd,
bg=color,
fg="white",
font=("Segoe UI", 11, "bold"),
relief="flat",
height=2,
width=20,
)
# Buttons (note: `self` refers to the app instance)
make_btn("Generate Random Color", self.generate_color, ACCENT).pack(side="top", pady=8)
make_btn("Copy HEX", self.copy_hex).pack(side="top", pady=8)
make_btn("Copy RGB", self.copy_rgb).pack(side="top", pady=8)
make_btn("Copy HSL", self.copy_hsl).pack(side="top", pady=8)
make_btn("About", self.show_about).pack(side="top", pady=20)
Explanation
make_btn()removes repetitive button‑creation code.commandlinks a button to its callback function.- Buttons provided: Generate, Copy HEX, Copy RGB, Copy HSL, About.
Step 6 – Build the Right Panel (Colour Preview)
# Right panel container
right = tk.Frame(root, bg=APP_BG)
right.pack(side="right", fill="both", expand=True)
# Card that holds the preview and values
self.result_card = tk.Frame(right, bg=PANEL_BG)
self.result_card.pack(padx=30, pady=40, fill="both", expand=True)
# Title
tk.Label(
self.result_card,
text="Color Preview",
bg=PANEL_BG,
fg=TEXT_CLR,
font=("Segoe UI", 16, "bold")
).pack(pady=(20, 10))
# Colour preview rectangle
self.color_preview = tk.Frame(self.result_card, bg="#333333", width=300, height=200)
self.color_preview.pack(pady=(10, 20))
self.color_preview.pack_propagate(False) # keep fixed size
Explanation
self.color_previewis a rectangular area that will display the generated colour.pack_propagate(False)stops the frame from resizing to fit its children.
Step 7 – Display Colour Values (HEX, RGB, HSL)
self.hex_label = tk.Label(
self.result_card,
text="HEX: --",
bg=PANEL_BG,
fg=ACCENT,
font=("Segoe UI", 14, "bold")
)
self.hex_label.pack(pady=5)
self.rgb_label = tk.Label(
self.result_card,
text="RGB: --",
bg=PANEL_BG,
fg=TEXT_CLR,
font=("Segoe UI", 14, "bold")
)
self.rgb_label.pack(pady=5)
self.hsl_label = tk.Label(
self.result_card,
text="HSL: --",
bg=PANEL_BG,
fg=SUBTEXT_CLR,
font=("Segoe UI", 14, "bold")
)
self.hsl_label.pack(pady=5)
Explanation
- These three labels are updated each time a new colour is generated, showing the colour in HEX, RGB, and HSL formats.
Step 8 – Generate Random Colours
def generate_color(self):
"""Create a random colour, update UI."""
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
# HEX string
self.current_color = f"#{r:02X}{g:02X}{b:02X}"
# Convert to HSL (colorsys uses HLS order)
h, l, s = colorsys.rgb_to_hls(r / 255, g / 255, b / 255)
hsl_str = f"{int(h * 360)}, {int(s * 100)}%, {int(l * 100)}%"
# Update UI
self.color_preview.config(bg=self.current_color)
self.hex_label.config(text=f"HEX: {self.current_color}")
self.rgb_label.config(text=f"RGB: {r}, {g}, {b}")
self.hsl_label.config(text=f"HSL: {hsl_str}")
Explanation
- Random values for R, G, B are generated.
- They are formatted into a HEX string (
#RRGGBB). colorsys.rgb_to_hlsconverts the RGB tuple to HSL (note the H‑L‑S order).- The preview rectangle and the three labels are refreshed.
Step 9 – Copy‑to‑Clipboard Functions
def copy_hex(self):
"""Copy the HEX value to the clipboard."""
self.root.clipboard_clear()
self.root.clipboard_append(self.current_color)
messagebox.showinfo("Copied", f"{self.current_color} copied to clipboard!")
def copy_rgb(self):
"""Copy the RGB value to the clipboard."""
rgb_text = self.rgb_label.cget("text").replace("RGB: ", "")
self.root.clipboard_clear()
self.root.clipboard_append(rgb_text)
messagebox.showinfo("Copied", f"{rgb_text} copied to clipboard!")
def copy_hsl(self):
"""Copy the HSL value to the clipboard."""
hsl_text = self.hsl_label.cget("text").replace("HSL: ", "")
self.root.clipboard_clear()
self.root.clipboard_append(hsl_text)
messagebox.showinfo("Copied", f"{hsl_text} copied to clipboard!")
Explanation
- Each function clears the clipboard, appends the relevant colour string, and shows a confirmation dialog.
Step 10 – (Optional) About Dialog
def show_about(self):
"""Display a simple About window."""
messagebox.showinfo(
"About MateTools",
"MateTools – Pro Random Color Generator\n"
"Created with Python & Tkinter.\n"
"© 2026 Your Name"
)
Step 11 – Run the Application
if __name__ == "__main__":
root = tk.Tk()
app = RandomColorGeneratorApp(root)
root.mainloop()
Full Source Code (Ready to Copy)
import sys
import os
import tkinter as tk
from tkinter import messagebox
import random
import colorsys
# -------------------------------------------------
# Theme constants
# -------------------------------------------------
APP_BG = "#121212"
PANEL_BG = "#1F1F1F"
BTN_BG = "#2C2C2C"
ACCENT = "#FF6F61"
TEXT_CLR = "#E0E0E0"
SUBTEXT_CLR = "#AAAAAA"
INPUT_BG = "#333333"
INPUT_FG = "#FFFFFF"
FONT = ("Segoe UI", 11)
# -------------------------------------------------
# Main application class
# -------------------------------------------------
class RandomColorGeneratorApp:
def __init__(self, root):
self.root = root
root.title("MateTools – Pro Random Color Generator")
root.geometry("1000x620")
root.configure(bg=APP_BG)
root.resizable(False, False)
# ---------- Left panel ----------
left = tk.Frame(root, bg=PANEL_BG, width=420)
left.pack(side="left", fill="y")
tk.Label(
left,
text="MateTools",
bg=PANEL_BG,
fg=ACCENT,
font=("Segoe UI", 20, "bold")
).pack(padx=16, pady=(18, 10))
tk.Label(
left,
text="Pro Random Color Generator",
bg=PANEL_BG,
fg=TEXT_CLR,
font=("Segoe UI", 14, "bold")
).pack(anchor="w", padx=16, pady=(0, 2))
# Buttons
btn_frame = tk.Frame(left, bg=PANEL_BG)
btn_frame.pack(fill="x", padx=16, pady=16)
def make_btn(text, cmd, color=BTN_BG):
return tk.Button(
btn_frame,
text=text,
command=cmd,
bg=color,
fg="white",
font=("Segoe UI", 11, "bold"),
relief="flat",
height=2,
width=20,
)
make_btn("Generate Random Color", self.generate_color, ACCENT).pack(side="top", pady=8)
make_btn("Copy HEX", self.copy_hex).pack(side="top", pady=8)
make_btn("Copy RGB", self.copy_rgb).pack(side="top", pady=8)
make_btn("Copy HSL", self.copy_hsl).pack(side="top", pady=8)
make_btn("About", self.show_about).pack(side="top", pady=20)
# ---------- Right panel ----------
right = tk.Frame(root, bg=APP_BG)
right.pack(side="right", fill="both", expand=True)
self.result_card = tk.Frame(right, bg=PANEL_BG)
self.result_card.pack(padx=30, pady=40, fill="both", expand=True)
tk.Label(
self.result_card,
text="Color Preview",
bg=PANEL_BG,
fg=TEXT_CLR,
font=("Segoe UI", 16, "bold")
).pack(pady=(20, 10))
self.color_preview = tk.Frame(self.result_card, bg="#333333", width=300, height=200)
self.color_preview.pack(pady=(10, 20))
self.color_preview.pack_propagate(False)
# Value labels
self.hex_label = tk.Label(
self.result_card,
text="HEX: --",
bg=PANEL_BG,
fg=ACCENT,
font=("Segoe UI", 14, "bold")
)
self.hex_label.pack(pady=5)
self.rgb_label = tk.Label(
self.result_card,
text="RGB: --",
bg=PANEL_BG,
fg=TEXT_CLR,
font=("Segoe UI", 14, "bold")
)
self.rgb_label.pack(pady=5)
self.hsl_label = tk.Label(
self.result_card,
text="HSL: --",
bg=PANEL_BG,
fg=SUBTEXT_CLR,
font=("Segoe UI", 14, "bold")
)
self.hsl_label.pack(pady=5)
# -------------------------------------------------
# Functional methods
# -------------------------------------------------
def
## Step 10: About Dialog
```python
def show_about(self):
messagebox.showinfo(
"About",
"MateTools – Pro Random Color Generator\n\n"
"• Generate random colors instantly\n"
"• View HEX, RGB, and HSL values\n"
"• Copy color values to clipboard\n\n"
"Built by MateTools"
)
Explanation:
Shows information about the app in a pop‑up.
Step 11: Run the App
Finally, we run the Tkinter event loop:
if __name__ == "__main__":
root = tk.Tk()
RandomColorGeneratorApp(root)
root.mainloop()
Explanation:
Tk()creates the main window.mainloop()starts the GUI and waits for user interactions.
✅ Congratulations!