使用 Python 內建 tkinter 快速構建桌面抽獎程式,展示事件驅動程式設計、非阻塞定時器、檔案資料載入與遮罩顯示等實用技巧。
App 類別封裝 UI 元件與邏輯after(ms, callback) 實現非阻塞動畫迴圈StringVar 雙向綁定輸入框顯示yaojiang.txt 讀取參加者名單(格式:姓名:電話)
import tkinter as tk
import random
class LotteryApp:
def __init__(self, root):
self.root = root
self.root.title("簡易抽獎系統")
self.stop_flag = False
self.participants = self.load_participants()
# UI 佈局
frame = tk.Frame(root)
frame.pack(padx=10, pady=10)
self.var = tk.StringVar(value="點擊開始")
entry = tk.Entry(frame, textvariable=self.var, font=('微軟正黑體', 24), width=20, justify='center', bd=5)
entry.pack(pady=10)
btn_frame = tk.Frame(frame)
btn_frame.pack()
tk.Button(btn_frame, text='開始', fg='red', font=('微軟正黑體', 14), width=8, command=self.start).pack(side=tk.LEFT, padx=5)
tk.Button(btn_frame, text='停止', fg='blue', font=('微軟正黑體', 14), width=8, command=self.stop).pack(side=tk.LEFT, padx=5)
def load_participants(self):
"""讀取並遮罩電話號碼:前4後4顯示,中間4碼替換為 xxxx"""
try:
with open('yaojiang.txt', 'r', encoding='utf-8') as f:
lines = [line.strip() for line in f if line.strip()]
except FileNotFoundError:
return ["(找不到名單檔案)"]
result = []
for line in lines:
parts = line.split(':', 1)
if len(parts) == 2:
name, phone = parts
if len(phone) >= 12:
masked = f"{phone[:4]}xxxx{phone[8:12]}"
else:
masked = phone
result.append(f"{name}:{masked}")
else:
result.append(line)
return result
def start(self):
self.stop_flag = False
self.animate()
def stop(self):
self.stop_flag = True
def animate(self):
if self.stop_flag:
return
winner = random.choice(self.participants)
self.var.set(winner)
# 每 50ms 更新一次,形成滾動效果
self.root.after(50, self.animate)
if __name__ == '__main__':
root = tk.Tk()
app = LotteryApp(root)
root.mainloop()
張三:0912345678
李四:0923456789
王五:0934567890
| 技術點 | 說明 |
|---|---|
root.after(ms, func) | 非阻塞定時器,回傳 ID 可用 after_cancel 取消。比 time.sleep 不會凍結 GUI。 |
StringVar | Tkinter 變數類別,綁定 Entry/Label 文字,修改變數自動更新 UI。 |
| 電話遮罩 | 切片 phone[:4] + 'xxxx' + phone[8:12] 保護隱私。 |
| 隨機選取 | random.choice(list) 等機率抽取。 |
Listbox + Scrollbar)random.choices(population, weights))ttk 主題元件提升外觀pyinstaller --onefile --noconsole lottery.py這個範例展示了 Tkinter 核心觀念,適合作為桌面小工具開發的起點。