本文目录导读:

我来为你提供一个简单易用的抽奖脚本,包含几种不同的实现方式:
最简单的Python抽奖脚本(命令行版)
import random
# 参与抽奖的人员名单
participants = [
"张三", "李四", "王五", "赵六", "孙七",
"周八", "吴九", "郑十", "陈一", "刘二"
]
print("🎉 抽奖开始!")
print(f"共有 {len(participants)} 人参与抽奖")
# 随机抽取一个中奖者
winner = random.choice(participants)
print(f"🎊 恭喜 {winner} 中奖!")
进阶版:可设置多个奖项
import random
import time
# 参与者名单
participants = [
"张三", "李四", "王五", "赵六", "孙七",
"周八", "吴九", "郑十", "陈一", "刘二",
"张三丰", "李白", "杜甫", "白居易", "苏轼"
]
def lottery(participants, awards):
"""抽奖主函数"""
remaining = participants.copy()
print("🎯 抽奖开始!")
print(f"参与人数:{len(remaining)} 人")
print(f"奖项设置:{', '.join(awards)}")
print("-" * 30)
results = {}
for award in awards:
if not remaining:
print("❌ 没有足够的参与者!")
break
# 模拟抽奖动画
print(f"\n【{award}】抽取中...")
for _ in range(3):
print("🎲 抽奖中" + "." * 3)
time.sleep(0.5)
winner = random.choice(remaining)
remaining.remove(winner)
results[award] = winner
print(f"🎉 {winner} 获得【{award}】!")
print("-" * 30)
print("📋 抽奖结果汇总:")
for award, winner in results.items():
print(f"🏆 {award}: {winner}")
return results
# 使用示例
awards = ["一等奖", "二等奖", "三等奖"] # 奖项设置
lottery(participants, awards)
带GUI界面的抽奖程序(tkinter)
import tkinter as tk
import random
class LotteryApp:
def __init__(self, root):
self.root = root
self.root.title("抽奖程序")
self.root.geometry("500x400")
self.participants = []
self.winners = []
self.setup_ui()
def setup_ui(self):
# 参与者输入区域
tk.Label(self.root, text="请输入参与者姓名(用逗号分隔):", font=("Arial", 12)).pack(pady=10)
self.input_entry = tk.Text(self.root, height=2, width=40)
self.input_entry.pack(pady=5)
# 按钮区域
btn_frame = tk.Frame(self.root)
btn_frame.pack(pady=10)
tk.Button(btn_frame, text="添加参与者", command=self.add_participants,
bg="lightblue", width=12).grid(row=0, column=0, padx=5)
tk.Button(btn_frame, text="开始抽奖", command=self.start_lottery,
bg="lightgreen", width=12).grid(row=0, column=1, padx=5)
tk.Button(btn_frame, text="清空结果", command=self.clear_results,
bg="lightcoral", width=12).grid(row=0, column=2, padx=5)
# 结果显示区域
self.result_label = tk.Label(self.root, text="", font=("Arial", 14, "bold"))
self.result_label.pack(pady=20)
# 参与者列表显示
tk.Label(self.root, text="当前参与者:", font=("Arial", 10)).pack()
self.participants_list = tk.Label(self.root, text="", font=("Arial", 10))
self.participants_list.pack(pady=5)
def add_participants(self):
text = self.input_entry.get("1.0", "end-1c")
names = [name.strip() for name in text.split(",") if name.strip()]
names = [name.strip() for name in ",".join(names).split(",") if name.strip()]
self.participants.extend(names)
self.input_entry.delete("1.0", "end")
self.update_participants_display()
def start_lottery(self):
if not self.participants:
self.result_label.config(text="⚠️ 请先添加参与者!")
return
available = [p for p in self.participants if p not in self.winners]
if not available:
self.result_label.config(text="⚠️ 所有参与者都已中奖!")
return
winner = random.choice(available)
self.winners.append(winner)
self.result_label.config(text=f"🎉 恭喜 {winner} 中奖!", fg="red")
def clear_results(self):
self.winners = []
self.result_label.config(text="", fg="black")
def update_participants_display(self):
text = ",".join(self.participants)
self.participants_list.config(text=text)
if __name__ == "__main__":
root = tk.Tk()
app = LotteryApp(root)
root.mainloop()
Web版抽奖(HTML+JavaScript)
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">在线抽奖</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
.input-area {
margin-bottom: 20px;
}
textarea {
width: 100%;
height: 80px;
margin-bottom: 10px;
}
button {
padding: 10px 20px;
margin: 5px;
cursor: pointer;
}
#result {
font-size: 24px;
color: red;
margin-top: 20px;
text-align: center;
}
#participants {
margin-top: 20px;
color: #666;
}
</style>
</head>
<body>
<h2>🎯 在线抽奖</h2>
<div class="input-area">
<textarea id="names" placeholder="请输入参与者姓名,用逗号分隔"></textarea>
<button onclick="addParticipants()">添加参与者</button>
<button onclick="resetAll()">重置所有</button>
</div>
<div id="result"></div>
<button onclick="startLottery()">🎲 开始抽奖</button>
<div id="participants"></div>
<script>
let participants = [];
let winners = [];
function addParticipants() {
const input = document.getElementById('names').value;
const names = input.split(/[,,\n]/).map(n => n.trim()).filter(n => n);
participants = participants.concat(names);
document.getElementById('names').value = '';
updateDisplay();
}
function startLottery() {
if (participants.length === 0) {
document.getElementById('result').innerHTML = '⚠️ 请先添加参与者!';
return;
}
const available = participants.filter(p => !winners.includes(p));
if (available.length === 0) {
document.getElementById('result').innerHTML = '⚠️ 所有参与者都已中奖!';
return;
}
// 增加动画效果
let count = 0;
const animation = setInterval(() => {
const randomName = available[Math.floor(Math.random() * available.length)];
document.getElementById('result').innerHTML = `🎲 ${randomName}`;
count++;
if (count > 10) {
clearInterval(animation);
const winner = available[Math.floor(Math.random() * available.length)];
winners.push(winner);
document.getElementById('result').innerHTML = `🎉 恭喜 ${winner} 中奖!`;
updateDisplay();
}
}, 100);
}
function resetAll() {
participants = [];
winners = [];
document.getElementById('result').innerHTML = '';
document.getElementById('names').value = '';
updateDisplay();
}
function updateDisplay() {
document.getElementById('participants').innerHTML =
`当前参与者:${participants.join(',')}`;
}
</script>
</body>
</html>
使用说明
- Python版本:保存为
.py文件,运行python lottery.py - GUI版本:需要tkinter库(Python自带)
- Web版本:保存为
.html文件,直接用浏览器打开
功能特点
- ✅ 随机抽取,公平公正
- ✅ 支持多人参与
- ✅ 可设置多个奖项
- ✅ 防止重复中奖(中奖者自动排除)
- ✅ 美观的界面效果
选择最适合你需求的版本,直接复制使用即可!