Python과 Tkinter로 미국 복권 번호 생성기 만들기

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

Source: Dev.to

🎲 로또 번호 생성기 – 데스크톱 앱 (Python + Tkinter)

📦 Step 1 – 필요한 라이브러리 가져오기

import sys
import os
import random
import tkinter as tk
from tkinter import messagebox
모듈용도
tkinterGUI 생성
random로또 번호 생성
messagebox팝업 표시 (예: About 대화상자)
sys, os시스템 수준 유틸리티 (선택 사항)

🎨 Step 2 – 앱 테마 정의

# ── Colours ───────────────────────────────────────
APP_BG      = "#121212"   # 전체 앱 배경
PANEL_BG    = "#1F1F1F"   # 사이드바 패널 배경
BTN_BG      = "#2C2C2C"   # 기본 버튼 배경
ACCENT      = "#FF6F61"   # 강조 요소 (예: 선택된 로또)
TEXT_CLR    = "#E0E0E0"   # 기본 텍스트 색
SUBTEXT_CLR = "#AAAAAA"   # 보조 텍스트 색
BALL_BG     = "#333333"   # 일반 볼 배경
BALL_FG     = "#FFFFFF"   # 일반 볼 전경

# ── Font ─────────────────────────────────────────
FONT = ("Segoe UI", 11)

색상 코드나 폰트는 필요에 따라 자유롭게 조정하세요.

🗂️ Step 3 – 로또 프리셋

LOTTERY_PRESETS = {
    "Powerball": {
        "main_numbers": (1, 69),   # 5개의 흰색 볼 범위
        "main_count": 5,
        "special_numbers": (1, 26),# 파워볼(빨강) 범위
        "special_count": 1,
    },
    "Mega Millions": {
        "main_numbers": (1, 70),   # 5개의 흰색 볼 범위
        "main_count": 5,
        "special_numbers": (1, 25),# 메가볼(금색) 범위
        "special_count": 1,
    },
}
  • main_numbers → 일반(흰색) 번호
  • special_numbers → 파워볼 / 메가볼
  • main_count & special_count → 추첨할 번호 개수

🏗️ Step 4 – 메인 앱 클래스

class LotteryGeneratorApp:
    def __init__(self, root):
        self.root = root
        root.title("MateTools – Lottery Number Generator US Standard")
        root.geometry("1000x520")
        root.configure(bg=APP_BG)
        root.resizable(False, False)

        # -----------------------------------------------------------------
        # Build UI (left panel, right panel, etc.) – see the following steps
        # -----------------------------------------------------------------
  • root.title – 창 제목
  • root.geometry – 고정 크기 (1000 × 520)
  • root.resizable(False, False) – 크기 조절 비활성화

📐 Step 5 – 왼쪽 패널 (사이드바) 만들기

# ----- Container -------------------------------------------------
left = tk.Frame(root, bg=PANEL_BG, width=420)
left.pack(side="left", fill="y")

# ----- Header ----------------------------------------------------
header = tk.Frame(left, bg=PANEL_BG)
header.pack(fill="x", padx=16, pady=(18, 10))

tk.Label(
    header,
    text="MateTools",
    bg=PANEL_BG,
    fg=ACCENT,
    font=("Segoe UI", 20, "bold")
).pack(side="left")

Frame – 위젯을 그룹화하는 일반 컨테이너
Label – 정적 텍스트 표시

# ----- Separator -------------------------------------------------
tk.Frame(left, bg=ACCENT, height=2).pack(fill="x", padx=16, pady=(0, 14))

# ----- Title & Description ----------------------------------------
tk.Label(
    left,
    text="Lottery Number Generator",
    bg=PANEL_BG,
    fg=TEXT_CLR,
    font=("Segoe UI", 14, "bold")
).pack(anchor="w", padx=16, pady=(0, 2))

tk.Label(
    left,
    text="Generate random numbers for Powerball / Mega Millions",
    bg=PANEL_BG,
    fg=SUBTEXT_CLR,
    font=("Segoe UI", 10)
).pack(anchor="w", padx=16, pady=(0, 16))

🎛️ Step 6 – 로또 선택 버튼

self.lottery_var = tk.StringVar(value="Powerball")
self.lottery_buttons = {}

btn_frame = tk.Frame(left, bg=PANEL_BG)
btn_frame.pack(fill="x", padx=16, pady=(0, 16))

f```

```python
or lottery in LOTTERY_PRESETS.keys():
    btn = tk.Button(
        btn_frame,
        text=lottery,
        command=lambda l=lottery: self.select_lottery(l),
        bg=BTN_BG if lottery != "Powerball" else ACCENT,
        fg="white" if lottery == "Powerball" else TEXT_CLR,
        font=FONT,
        relief="flat",
        height=2,
        width=18
    )
    btn.pack(side="left", expand=True, padx=4)
    self.lottery_buttons[lottery] = btn
  • StringVar – 현재 선택된 복권을 추적합니다.
  • lambda l=lottery – 콜백에서 현재 루프 값을 캡처합니다.

🔘 Step 7 – “Generate” & “About” 버튼

btn_frame2 = tk.Frame(left, bg=PANEL_BG)
btn_frame2.pack(fill="x", padx=16, pady=16)

def make_btn(text, cmd, color=BTN_BG):
    return tk.Button(
        btn_frame2,
        text=text,
        command=cmd,
        bg=color,
        fg="white",
        font=("Segoe UI", 11, "bold"),
        relief="flat",
        height=2,
        width=18
    )

make_btn("Generate Numbers", self.generate_numbers).pack(side="left", expand=True, padx=4)
make_btn("About", self.show_about, ACCENT).pack(side="left", expand=True, padx=4)

make_btn – 버튼 생성 코드를 반복하지 않도록 하는 작은 헬퍼 함수입니다.

📊 Step 8 – 오른쪽 패널 (결과 영역)

right = tk.Frame(root, bg=APP_BG)
right.pack(side="right", fill="both", expand=True)

self.stats_card = tk.Frame(right, bg=PANEL_BG)
self.stats_card.pack(padx=30, pady=40, fill="both", expand=True)

tk.Label(
    self.stats_card,
    text="Generated Numbers",
    bg=PANEL_BG,
    fg=TEXT_CLR,
    font=("Segoe UI", 14, "bold")
).pack(pady=(20, 10))

self.numbers_frame = tk.Frame(self.stats_card, bg=PANEL_BG)
self.numbers_frame.pack(pady=20)

numbers_frame – 색상이 입혀진 “볼” 라벨들을 담을 프레임입니다.

🎲 Step 9 – 복권 번호 생성 로직

def generate_numbers(self):
    # ---- Clear any previous results ------------------------------
    for widget in self.numbers_frame.winfo_children():
        widget.destroy()

    # ---- Determine which lottery is active -----------------------
    lottery = self.lottery_var.get()
    preset = LOTTERY_PRESETS[lottery]

    # ---- Draw main numbers (unique) -------------------------------
    main = random.sample(
        range(preset["main_numbers"][0], preset["main_numbers"][1] + 1),
        preset["main_count"]
    )
    # ---- Draw special number(s) ----------------------------------
    special = random.sample(
        range(preset["special_numbers"][0], preset["special_numbers"][1] + 1),
        preset["special_count"]
    )

    main.sort()          # optional: show the white balls in order
  • random.sample중복되지 않는 번호를 보장합니다.
  • 메인 번호를 정렬하면 공식 티켓에 표시되는 방식과 동일하게 됩니다.

🔴 Step 10 – 번호를 컬러볼로 표시

# ---- White (main) balls -----------------------------------------
for num in main:
    ball = tk.Label(
        self.numbers_frame,
        text=str(num),
        bg="#1E90FF",          # 밝은 파란색 (화이트볼)
        fg="white",
        font=("Segoe UI", 16, "bold"),
        width=4,
        height=2,
        relief="raised",
        bd=2
    )
    ball.pack(side="left", padx=5)

# ---- Special (Powerball / Mega Ball) ball -----------------------
for num in special:
    ball = tk.Label(
        self.numbers_frame,
        text=str(num),
        bg="#FF4500",          # 주황‑빨강 (Powerball) / 메가볼은 금색으로 바꿀 수 있음
        fg="white",
        font=("Segoe UI", 16, "bold"),
        width=4,
        height=2,
        relief="raised",
        bd=2
    )
    ball.pack(side="left", padx=5)

Note: 위 스니펫은 원문에서 갑자기 끝납니다. 전체 구현에서는 추가 UI 업데이트(예: “클립보드에 복사” 버튼)와 select_lottery, show_about 메서드, 그리고 메인 루프 시작 코드를 이어서 작성해야 합니다.

def select_lottery(self, name):
    self.lottery_var.set(name)
    # ...
Update button colours to reflect the selection
    for l, btn in self.lottery_buttons.items():
        if l == name:
            btn.configure(bg=ACCENT, fg="white")
        else:
            btn.configure(bg=BTN_BG, fg=TEXT_CLR)

def show_about(self):
    messagebox.showinfo(
        "About MateTools",
        "Lottery Number Generator\n"
        "Author: Your Name\n"
        "Generate random Powerball / Mega Millions numbers."
    )

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

✅ Finished!

Run the script, pick Powerball or Mega Millions, hit Generate Numbers, and watch the colourful balls appear. The About button displays a simple info dialog.

Ideas for Extension

  • Add a “Copy to clipboard” feature.
  • Store the last‑generated set in a file.
  • Expand the UI with more lotteries (e.g., EuroJackpot, Lotto USA).

Happy coding! 🎉

코드 스니펫

# Example widget configuration
eight = 2
relief = "raised"
bd = 2

ball.pack(side="left", padx=5)

색상 전설

  • 파란 공 → 메인 번호
  • 주황색 공 → 특수 번호 (Powerball / Mega Ball)

11단계: About 팝업 추가

def show_about(self):
    messagebox.showinfo(
        "About",
        "MateTools – Lottery Number Generator\n\n"
        "• Random number generation\n"
        "• Presets for Powerball and Mega Millions\n\n"
        "Built by MateTools"
    )

Step 12: 앱 실행

if __name__ == "__main__":
    root = tk.Tk()
    LotteryGeneratorApp(root)
    root.mainloop()
  • root.mainloop() → Tkinter GUI 루프를 시작합니다

이것으로 끝! 이제 현대적이고 초보자 친화적인 인터페이스를 갖춘 완전한 기능의 미국 로또 번호 생성기가 준비되었습니다.

0 조회
Back to Blog

관련 글

더 보기 »

Java 개발자를 위한 Python OOP

간단한 Java Square 클래스를 Python으로 변환하기 아래는 Java로 작성된 기본 Square 클래스를 동등한 Python 구현으로 단계별(step‑by‑step) 변환한 내용입니다.

나만의 함수

사용자 정의 함수: 특정 작업을 수행하기 위해 작성된 코드 블록. 함수의 선언·정의 - 인자 (argument) = 매개변수 (parameter) - 수행문 - 반환값 (return) python def 함수_이름(인자1, 인자2, …): 수행문 1 수행문 2 return 인자의 종류…