使用 Python 內建 tkinter 庫,不需額外依賴即可快速構建桌面 GUI 應用。本文提供一個功能完整的抽獎程式:從文本文件讀取參與者名單、手機號碼脫敏顯示、開始/停止按鈕控制、高頻閃爍動畫模擬抽獎過程。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tkinter as tk
import random
import time
class LotteryApp:
def __init__(self, root):
self.root = root
self.root.title("簡易抽獎系統")
self.root.geometry("400x150")
# 變數
self.var = tk.StringVar(value="點擊開始抽獎")
self.running = False
self.participants = []
# 介面佈局
frame = tk.Frame(root)
frame.pack(pady=20, padx=20, fill=tk.BOTH, expand=True)
# 顯示區
entry = tk.Entry(frame, textvariable=self.var, font=('微軟正黑體', 18),
justify='center', state='readonly', bd=5)
entry.pack(fill=tk.X, pady=10)
# 按鈕區
btn_frame = tk.Frame(frame)
btn_frame.pack()
self.btn_start = tk.Button(btn_frame, text='開始', fg='red', width=10,
command=self.start_lottery)
self.btn_start.pack(side=tk.LEFT, padx=10)
self.btn_stop = tk.Button(btn_frame, text='停止', fg='blue', width=10,
command=self.stop_lottery, state=tk.DISABLED)
self.btn_stop.pack(side=tk.LEFT, padx=10)
# 載入名單
self.load_participants()
def load_participants(self):
"""從 yaojiang.txt 讀取並脫敏手機號"""
try:
with open('yaojiang.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
line = line.strip()
if not line: continue
# 格式假設: 姓名:手機號
parts = line.split(':', 1)
if len(parts) == 2:
name, phone = parts
# 脫敏: 保留前4後4,中間4位替換為 xxxx
masked = f"{name}:{phone[:4]}xxxx{phone[-4:]}" if len(phone) >= 8 else line
self.participants.append(masked)
else:
self.participants.append(line)
except FileNotFoundError:
self.participants = ["測試用戶1:138xxxx5678", "測試用戶2:139xxxx1234"]
print("未找到 yaojiang.txt,使用預設名單")
def start_lottery(self):
if not self.participants:
self.var.set("名單為空!")
return
self.running = True
self.btn_start.config(state=tk.DISABLED)
self.btn_stop.config(state=tk.NORMAL)
self.animate()
def stop_lottery(self):
self.running = False
self.btn_start.config(state=tk.NORMAL)
self.btn_stop.config(state=tk.DISABLED)
def animate(self):
if not self.running:
return
# 隨機選取顯示
self.var.set(random.choice(self.participants))
# 50ms 後繼續 (約 20fps)
self.root.after(50, self.animate)
if __name__ == '__main__':
root = tk.Tk()
app = LotteryApp(root)
root.mainloop()
| 模組 | 實現要點 |
|---|---|
| 資料來源 | 讀取 yaojiang.txt,格式 姓名:手機號,自動脫敏中間 4 碼 |
| 動畫引擎 | root.after(50, callback) 非阻塞定時器,約 20 FPS 閃爍 |
| 狀態機 | running 布林旗標控制動畫循環,按鈕狀態同步切換 |
| 隨機選取 | random.choice(list) 均勻分佈選取 |
| 介面響應 | 按鈕 state 切換防止重複點擊,readonly Entry 防誤編輯 |
張三:13812345678
李四:13987654321
王五:13711112222
趙六:13633334444
random.choices(population, weights=k) 實現概率差異winners.log,避免重複中獎winsound 或 pygame 播放音效pyinstaller --onefile --noconsole lottery.py 生成單檔 exe# -*- coding: utf-8 -*-after() 而非 time.sleep() 實現動畫'微軟正黑體' 改為 'DejaVu Sans' 或系統預設字體這個百行級小程式展示了 Tkinter 構建實用桌面工具的完整流程:資料讀取→業務邏輯→事件驅動 UI→狀態管理,是 GUI 入門的優秀練習專案。