Python과 Tkinter로 프로 랜덤 컬러 생성기 만들기

발행: (2026년 2월 18일 오후 02:19 GMT+9)
13 분 소요
원문: Dev.to

Source: Dev.to

파이썬과 Tkinter로 프로 수준의 랜덤 색상 생성기 만들기

소개

이 튜토리얼에서는 Tkinter GUI 라이브러리를 사용해 랜덤 색상 생성기를 만드는 과정을 단계별로 살펴봅니다. 완성된 애플리케이션은 버튼을 클릭할 때마다 새로운 색상을 생성하고, 해당 색상의 HEX 코드RGB 값을 화면에 표시합니다. 또한, 배경색을 실시간으로 업데이트하여 시각적인 피드백을 제공합니다.

준비물

  • Python 3.x (3.6 이상 권장)
  • 기본 Tkinter 모듈 (Python에 기본 포함)
  • random 모듈 (표준 라이브러리)

전체 코드

import tkinter as tk
import random

def random_color():
    """랜덤 색상을 생성하고 UI를 업데이트합니다."""
    # 0~255 사이의 랜덤 RGB 값 생성
    r = random.randint(0, 255)
    g = random.randint(0, 255)
    b = random.randint(0, 255)

    # HEX 문자열 생성 (예: #1A2B3C)
    hex_color = f'#{r:02X}{g:02X}{b:02X}'

    # 라벨에 색상 정보 표시
    hex_label.config(text=f'HEX: {hex_color}')
    rgb_label.config(text=f'RGB: ({r}, {g}, {b})')

    # 윈도우 배경색 변경
    root.configure(bg=hex_color)

# 메인 윈도우 설정
root = tk.Tk()
root.title('Random Color Generator')
root.geometry('300x200')
root.resizable(False, False)

# HEX 코드 라벨
hex_label = tk.Label(root, text='HEX: ', font=('Helvetica', 12))
hex_label.pack(pady=10)

# RGB 값 라벨
rgb_label = tk.Label(root, text='RGB: ', font=('Helvetica', 12))
rgb_label.pack(pady=10)

# 색상 생성 버튼
generate_btn = tk.Button(root, text='Generate Color', command=random_color,
                         font=('Helvetica', 12), bg='#4CAF50', fg='white')
generate_btn.pack(pady=20)

# 초기 색상 설정
random_color()

# 이벤트 루프 시작
root.mainloop()

코드 설명

1. random_color 함수

  • RGB 값 생성: random.randint(0, 255)를 세 번 호출해 빨강, 초록, 파랑 값을 얻습니다.
  • HEX 변환: f'#{r:02X}{g:02X}{b:02X}' 포맷 문자열을 사용해 2자리 16진수 형태로 변환합니다.
  • UI 업데이트:
    • hex_labelrgb_label에 각각 현재 색상의 HEX와 RGB 값을 표시합니다.
    • root.configure(bg=hex_color)를 호출해 메인 윈도우 배경색을 새 색상으로 바꿉니다.

2. Tkinter 위젯

위젯역할
root메인 윈도우 객체. 타이틀, 크기, 리사이즈 방지 등을 설정합니다.
hex_label / rgb_label현재 색상의 HEX와 RGB 정보를 텍스트로 보여줍니다.
generate_btn클릭 시 random_color 함수를 실행해 새로운 색상을 생성합니다.

3. 초기 색상 설정

random_color()를 한 번 호출해 프로그램이 시작될 때 바로 색상이 표시되도록 합니다. 이렇게 하면 사용자가 첫 화면부터 색상 변화를 확인할 수 있습니다.

확장 아이디어

  • 색상 히스토리: 생성된 색상을 리스트에 저장하고, 이전 색상으로 돌아가는 버튼을 추가합니다.
  • 색상 복사: 현재 HEX 코드를 클립보드에 복사하는 기능을 구현합니다 (root.clipboard_clear()root.clipboard_append() 사용).
  • 다크/라이트 모드: 라벨과 버튼 텍스트 색상을 배경색 대비가 잘 되도록 자동 조정합니다.
  • 색상 팔레트 저장: 사용자가 마음에 드는 색상을 파일(.json 또는 .txt)에 저장해 나중에 불러올 수 있게 합니다.

마무리

Tkinter와 파이썬 표준 라이브러리만으로도 충분히 시각적이고 인터랙티브한 애플리케이션을 만들 수 있습니다. 위 예제는 기본적인 구조를 보여주므로, 여기서 제시한 확장 아이디어를 적용해 자신만의 색상 도구를 만들어 보세요!

Source:

Random Color Generator Desktop App (Tkinter)

이 튜토리얼에서는 Python의 tkinter를 사용하여 무작위 색상을 생성하고 HEX, RGB, HSL 값을 표시하는 데스크톱 앱을 만드는 방법을 알아봅니다. 초보자도 따라 할 수 있도록 단계별로 나누어 설명합니다.

Step 1 – Import Required Modules

import sys
import os
import tkinter as tk
from tkinter import messagebox
import random
import colorsys

Explanation

ModulePurpose
tkinterGUI 구축
messagebox팝업 메시지 표시 (예: “클립보드에 복사됨”)
random무작위 색상 값 생성
colorsysRGB 값을 HSL 형식으로 변환

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

  • 일관된 배경, 버튼, 강조 색상 및 텍스트 색상을 사용해 현대적인 다크 테마를 구현합니다.
  • FONT는 레이블, 버튼 및 기타 텍스트 위젯에 적용됩니다.

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 – 메인 Tkinter 창.
  • title() – 창 제목을 설정합니다.
  • geometry() – 창 크기를 정의합니다.
  • resizable(False, False) – 창 크기 조절을 비활성화합니다.

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 – 위젯을 담는 컨테이너.
  • Label – 정적인 텍스트를 표시합니다.
  • pack() – 레이아웃 매니저; side="left"는 패널을 왼쪽에 고정합니다.

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()은 반복되는 버튼 생성 코드를 제거합니다.
  • command는 버튼을 해당 콜백 함수와 연결합니다.
  • 제공되는 버튼: 색상 생성, HEX 복사, RGB 복사, 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))

# C

> **Source:** ...

### colour preview rectangle
```python
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

설명

  • self.color_preview는 생성된 색상을 표시할 사각형 영역입니다.
  • pack_propagate(False)는 프레임이 자식 위젯에 맞춰 크기가 변하는 것을 방지합니다.

단계 7 – 색상 값 표시 (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)

설명

  • 이 세 개의 라벨은 새로운 색상이 생성될 때마다 업데이트되어 HEX, RGB, HSL 형식으로 색상을 보여줍니다.

단계 8 – 무작위 색상 생성

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}")

설명

  • R, G, B에 대한 무작위 값을 생성합니다.
  • 값을 HEX 문자열(#RRGGBB)로 포맷합니다.
  • colorsys.rgb_to_hls는 RGB 튜플을 HSL로 변환합니다(주의: H‑L‑S 순서).
  • 미리보기 사각형과 세 라벨을 새 값으로 갱신합니다.

단계 9 – 클립보드 복사 기능

def copy_hex(self):
    """Copy the current HEX value to the clipboard."""
    self.root.clipboard_clear()
    self.root.clipboard_append(self.current_color)
    messagebox.showinfo("Copied", f"HEX value {self.current_color} copied to clipboard.")

def copy_rgb(self):
    """Copy the current RGB value to the clipboard."""
    rgb_str = f"{self.current_color[1:3]}, {self.current_color[3:5]}, {self.current_color[5:]}"
    self.root.clipboard_clear()
    self.root.clipboard_append(rgb_str)
    messagebox.showinfo("Copied", f"RGB value {rgb_str} copied to clipboard.")

def copy_hsl(self):
    """Copy the current HSL value to the clipboard."""
    # Re‑calculate HSL to ensure consistency
    r, g, b = (int(self.current_color[i:i+2], 16) for i in (1, 3, 5))
    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)}%"
    self.root.clipboard_clear()
    self.root.clipboard_append(hsl_str)
    messagebox.showinfo("Copied", f"HSL value {hsl_str} copied to clipboard.")

설명

  • 각 함수는 클립보드를 비운 뒤 해당 색상 문자열을 복사하고, 확인 대화상자를 표시합니다.

단계 10 – 정보 대화상자

def show_about(self):
    """Display an About dialog with app information."""
    messagebox.showinfo(
        "About MateTools",
        "MateTools – Pro Random Color Generator\n"
        "Version: 1.0.0\n"
        "Author: Your Name\n"
        "Generate random colours and copy their HEX, RGB, or HSL values."
    )

단계 11 – 애플리케이션 실행

if __name__ == "__main__":
    root = tk.Tk()
    app = RandomColorGeneratorApp(root)
    root.mainloop()

설명

  • Tkinter 루트 창을 만들고, 앱 클래스를 인스턴스화한 뒤 이벤트 루프를 시작합니다.

복사 함수

def copy_hex(self):
    """Copy th

Explanation

  • 각 함수는 클립보드를 비우고, 해당 색상 문자열을 추가한 뒤 확인 대화 상자를 표시합니다.

Step 10 – (선택 사항) 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 – 애플리케이션 실행

if __name__ == "__main__":
    root = tk.Tk()
    app = RandomColorGeneratorApp(root)
    root.mainloop()

전체 소스 코드 (복사 준비 완료)

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
    # -------------------------------------------------
    # TODO: Implement generate_color, copy_hex, copy_rgb, copy_hsl, and show_about

10단계: 정보 대화 상자

def show_about(self):
    messagebox.showinfo(
        "About",
        "Mate
0 조회
Back to Blog

관련 글

더 보기 »