使用 Python 和 Tkinter 构建美国彩票号码生成器

发布: (2026年2月15日 GMT+8 13:04)
7 分钟阅读
原文: Dev.to

Source: Dev.to

(请提供您希望翻译的完整文本内容,我将为您翻译成简体中文并保留原始的 Markdown 格式。)

Source:

🎲 彩票号码生成器 – 桌面应用(Python + Tkinter)

📦 步骤 1 – 导入所需库

import sys
import os
import random
import tkinter as tk
from tkinter import messagebox
模块用途
tkinterGUI 创建
random生成彩票号码
messagebox显示弹出窗口(例如 About 对话框)
sys, os系统级工具(可选)

🎨 步骤 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)

随意调整颜色代码或字体,以匹配你的个人风格。

🗂️ 步骤 3 – 彩票预设

LOTTERY_PRESETS = {
    "Powerball": {
        "main_numbers": (1, 69),   # 5 个白球的取值范围
        "main_count": 5,
        "special_numbers": (1, 26),# Powerball(红球)的取值范围
        "special_count": 1,
    },
    "Mega Millions": {
        "main_numbers": (1, 70),   # 5 个白球的取值范围
        "main_count": 5,
        "special_numbers": (1, 25),# Mega Ball(金球)的取值范围
        "special_count": 1,
    },
}
  • main_numbers → 普通(白色)号码
  • special_numbers → Powerball / Mega Ball
  • main_countspecial_count → 各自抽取的号码数量

🏗️ 步骤 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) – 禁止窗口缩放

📐 步骤 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))

🎛️ 步骤 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))

Source:

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 – 为回调捕获当前循环的值。

🔘 第 7 步 – “生成” 与 “关于” 按钮

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 – 小型辅助函数,用来避免重复创建按钮的代码。

📊 第 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 – 用来放置彩色“球”标签的容器。

🎲 第 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 确保 唯一 的号码。
  • 对主号码进行排序可以模拟官方彩票打印时的排列方式。

🔴 第 10 步 – 将号码显示为彩色球

# ---- White (main) balls -----------------------------------------
for num in main:
    ball = tk.Label(
        self.numbers_frame,
        text=str(num),
        bg="#1E90FF",          # bright blue for white balls
        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",          # orange‑red for the Powerball / gold for Mega Ball
        fg="white",
        font=("Segoe UI", 16, "bold"),
        width=4,
        height=2,
        relief="raised",
        bd=2
    )
    ball.pack(side="left", padx=5)

注意: 上面的代码片段在原文中被截断。完整实现还会继续进行其他 UI 更新(例如“复制到剪贴板”按钮),以及 select_lotteryshow_about 方法和主循环的启动代码:

def select_lottery(self, name):
    self.lottery_var.set(name)
    #```

```python
# 更新按钮颜色以反映选择
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(
        "关于 MateTools",
        "彩票号码生成器\n"
        "作者: Your Name\n"
        "生成随机的 Powerball / Mega Millions 号码。"
    )

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

✅ 完成!

运行脚本,选择 PowerballMega Millions,点击 Generate Numbers,即可看到彩色球出现。About 按钮会显示一个简易信息对话框。

扩展思路

  • 添加 “复制到剪贴板” 功能。
  • 将最近生成的一组号码保存到文件。
  • 扩展 UI,加入更多彩票(例如 EuroJackpotLotto USA)。

祝编码愉快! 🎉

代码片段

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

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

颜色图例

  • 蓝色球 → 主号码
  • 橙色球 → 特殊号码(Powerball / Mega Ball)

第11步:添加关于弹出窗口

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

第12步:运行应用

if __name__ == "__main__":
    root = tk.Tk()
    LotteryGeneratorApp(root)
    root.mainloop()
  • root.mainloop() → 启动 Tkinter GUI 循环

就这样! 现在你已经拥有一个功能完整的美国彩票号码生成器,界面现代且适合初学者。

0 浏览
Back to Blog

相关文章

阅读更多 »