萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python Tkinter 彩票選號器:雙色球/大樂透隨機生成器實戰

專案展示

一個圖形界面小工具,一鍵生成中國福利彩票「雙色球」(紅球 6+藍球 1)與體育彩票「大樂透」(前區 5+後區 2)隨機號碼,支援歷史記錄滾動顯示、一鍵清空。

完整代碼


import tkinter as tk
from tkinter import ttk, font
import random

class LotteryPicker:
    def __init__(self, root):
        self.root = root
        root.title("彩票機選器")
        root.resizable(False, False)
        self._setup_style()
        self._build_ui()

    def _setup_style(self):
        self.title_font = font.Font(family="Microsoft YaHei", size=20, weight="bold")
        self.btn_font = font.Font(family="Microsoft YaHei", size=12)
        self.text_font = font.Font(family="Consolas", size=11)

    def _build_ui(self):
        # 頂部按鈕區
        btn_frame = ttk.Frame(self.root, padding=10)
        btn_frame.pack(fill=tk.X)

        ttk.Button(btn_frame, text="雙色球", style="Accent.TButton",
                   command=self.gen_double_color, width=15).pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text="大樂透", style="Accent.TButton",
                   command=self.gen_da_letou, width=15).pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text="清空記錄",
                   command=self.clear_history, width=15).pack(side=tk.LEFT, padx=5)

        # 歷史記錄區
        hist_frame = ttk.Frame(self.root, padding=(10,0,10,10))
        hist_frame.pack(fill=tk.BOTH, expand=True)

        self.history = tk.Text(hist_frame, width=50, height=18, font=self.text_font,
                               state=tk.DISABLED, wrap=tk.NONE)
        self.history.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

        vscroll = ttk.Scrollbar(hist_frame, orient=tk.VERTICAL, command=self.history.yview)
        vscroll.pack(side=tk.RIGHT, fill=tk.Y)
        self.history['yscrollcommand'] = vscroll.set

        hscroll = ttk.Scrollbar(self.root, orient=tk.HORIZONTAL, command=self.history.xview)
        hscroll.pack(fill=tk.X)
        self.history['xscrollcommand'] = hscroll.set

        # 標籤樣式
        self.history.tag_configure("red", foreground="#e74c3c")
        self.history.tag_configure("blue", foreground="#3498db")
        self.history.tag_configure("green", foreground="#27ae60")
        self.history.tag_configure("normal", foreground="#2c3e50")

    # ----- 核心算法 -----
    def _pick_unique(self, pool_size: int, count: int) -> list:
        """從 1..pool_size 不重複隨機選取 count 個,已排序"""
        return sorted(random.sample(range(1, pool_size + 1), count))

    def gen_double_color(self):
        """雙色球:紅球 1-33 選 6,藍球 1-16 選 1"""
        reds = self._pick_unique(33, 6)
        blue = random.randint(1, 16)
        self._append_history("雙色球", reds, [blue], "red", "blue")

    def gen_da_letou(self):
        """大樂透:前區 1-35 選 5,後區 1-12 選 2"""
        front = self._pick_unique(35, 5)
        back = self._pick_unique(12, 2)
        self._append_history("大樂透", front, back, "green", "blue")

    def _append_history(self, game: str, main: list, extra: list, main_color: str, extra_color: str):
        self.history.config(state=tk.NORMAL)
        line = f"[{game}] "
        for n in main:
            line += f"{n:02d} "
        line += "| "
        for n in extra:
            line += f"{n:02d} "
        line += "\n"
        self.history.insert("1.0", line)
        # 重新上色(簡化:按位置上色)
        self._colorize_last_line(main_color, extra_color)
        self.history.config(state=tk.DISABLED)
        self.history.see("1.0")

    def _colorize_last_line(self, main_color, extra_color):
        # 簡易上色:第一行
        line_start = "1.0"
        line_end = "2.0"
        text = self.history.get(line_start, line_end)
        # 找分隔符位置
        parts = text.split('|')
        if len(parts) == 2:
            main_part = parts[0]
            extra_part = parts[1]
            main_len = len(main_part)
            self.history.tag_add(main_color, "1.0", f"1.{main_len}")
            self.history.tag_add(extra_color, f"1.{main_len}", "2.0")

    def clear_history(self):
        self.history.config(state=tk.NORMAL)
        self.history.delete("1.0", tk.END)
        self.history.config(state=tk.DISABLED)

if __name__ == "__main__":
    root = tk.Tk()
    # 嘗試設置主題
    try:
        from tkinter import ttk
        style = ttk.Style()
        style.theme_use('vista' if 'vista' in style.theme_names() else 'clam')
        style.configure("Accent.TButton", font=("Microsoft YaHei", 12, "bold"))
    except:
        pass
    app = LotteryPicker(root)
    root.mainloop()

核心算法解析

random.sample(population, k)

從序列中**不重複**隨機選取 k 個元素,時間複雜度 O(k),底層使用集合/數組交換算法,比手寫 while len(res) 快得多且無偏。

號碼排序

彩票號碼慣例**升序顯示**,sorted() 保證輸出有序,便於對獎核對。

界面亮點

  • 只讀 Text + 雙向滾動條:歷史記錄只增不改,state=DISABLED 防止誤編輯,寫入時臨時啟用。
  • 標籤上色:紅球/藍球/前區/後區分色,視覺區分度高。
  • 響應式佈局:pack(fill=BOTH, expand=True) 適應窗口縮放。
  • 主題適配:嘗試使用系統原生主題,按鈕加粗突出。

擴展想法

  1. 歷史持久化:關閉時保存至 JSON,啟動載入。
  2. 統計分析:頻率統計、冷熱號圖表(matplotlib 嵌入)。
  3. 多期批量生成:一次生成 N 期,導出 Excel/CSV。
  4. 網絡同步開獎:爬取官方開獎數據自動對獎。
  5. 打包分發:pyinstaller --onefile --noconsole lottery.py 生成單文件 exe。

總結

不到 150 行代碼實現了功能完整、界面友好的彩票選號器,展示了 random.sample 高效去重採樣、Tkinter Text 標籤上色、滾動條雙向綁定、只讀文本編輯等實用技巧。適合作為 Python GUI 入門進階項目,亦可直接作為日常娛樂小工具使用。

copyright © 萬盛學電腦網 all rights reserved