python实现滚动抽奖(可加小机关)
实现的功能:
1.peopleList.csv 是参与抽奖名单
2.可以选择重复抽取或不重复抽取
3.可以设置每次抽取人数
4.抽动过程中可以让名单滚动起来
5.可以导出抽奖记录csv格式,默认以导出时间命名
*双击复位可以,指导人员(csv中前5名)*操作非常隐秘…
下面代码介绍:
第一步,自己写csv的读写,有pandas 为什么需要自己写,为了打包成exe更小,启动更快。
# -*- coding: utf-8 -*-
def read_csv(path):
try:
keys = []
list_dict = []
with open(path,'r',encoding='utf-8') as file:
for index,line in enumerate(file.readlines()):
if index == 0:
line = line[1:]
line = line.strip()
row = line.split(',')
keys = row
else:
line = line.strip()
row = line.split(',')
dict1 = {}
for index2,key in enumerate(keys):
dict1[key] = row[index2]
list_dict.append(dict1)
return list_dict
except Exception as e:
return []
def to_csv(name,list_dict):
# print(list_dict)
try:
with open(name, 'w', encoding='utf-8') as file:
s = ''
for index,dict1 in enumerate(list_dict):
for key in dict1:
dict1[key] = str(dict1[key])
if index == 0:
line1 = '\ufeff' + ','.join(dict1.keys()) + '\n'
s = s + line1
lineX = ','.join(dict1.values()) + '\n'
s = s + lineX
file.write(s)
except Exception as e:
print(e)
第二步,使用tkinter完成UI
window = Tk()
window.config(background="#134388")
window.attributes("-fullscreen", False)
w, h = window.winfo_screenwidth(), window.winfo_screenheight()
window.geometry("%dx%d" % (w, h))
window.title('抽奖小程序')
getPeopleList()
top2 = Toplevel()
top2.config(background="#134388")
top2.geometry('380x230+100+100')
top2.resizable(0, 0)
top2.title('抽奖小程序')
top2.attributes("-topmost", True) #使该窗口保持在所有其他窗口之上
frame = Frame(window, bg='lightgreen') # 创建一个框架
frame.pack(fill=BOTH,expand=YES)
var_result = StringVar()
var_result.set('即将开始!')
resultLable2 = Label(frame,textvariable=var_result,justify='center',bg="#134388",fg='white',wraplength=w-500)
resultLable2.pack(fill=BOTH, expand=YES)
resultLable2.config(font='Helvetica -50 bold')
noteLable = Label(top2,text="请输入抽奖人数:")
noteLable.place(anchor=NW, x=40, y=30)
input = Entry(top2, show=None)
input.place(anchor=NW, x=160, y=30)
var1 = IntVar()
Checkbutton = Checkbutton(top2,text="不重复抽取",variable=var1,onvalue=0,
offvalue=1)
Checkbutton.place(anchor=NW, x=40, y=60)
startBt = Button(top2,text="开始抽人", command=lambda: randomRun())
# startBt.bind("<Button-1>", onLeft)
# startBt.bind("<Double-Button-1>",Double_click)
confirmBt = Button(top2,text="确定", command=lambda: finalResult())
confirmBt['state'] = DISABLED
resetBt = Button(top2, text="复位", command=lambda: reset())
resetBt['state'] = DISABLED
# resetBt.bind("<Button-1>", onLeft)
resetBt.bind("<Double-Button-1>", Double_click)
exportBt = Button(top2,text="导出", command=lambda: exportResult())
exportBt['state'] = DISABLED
startBt.place(anchor=NW, x=40, y=120)
confirmBt.place(anchor=NW, x=160, y=120)
resetBt.place(anchor=NW, x=250, y=120)
exportBt.place(anchor=NW, x=250, y=150)
window.mainloop()
获取csv内的人员
def getPeopleList():
global people_dict
global people_list,people_list2,people_list3
global luck_people_list1, luck_people_list2
people_dict = wb_readcsv.read_csv(os.path.dirname(os.path.realpath(sys.argv[0]))+'/peopleList.csv')
people_list = [n for n in range(0, len(people_dict))]
people_list2 = copy.deepcopy(people_list)
people_list3 = people_list2[:5] #需要内定名单
people_list2 = people_list2[5:] #正常抽取名单
luck_people_list1 = []
luck_people_list2 = []
是否重复抽取
def randomRun():
global is_run
global people_list, people_list2
if is_run:#此部分用于避免多次点击开始造成程序重复执行的错误
return
is_run = True
num = insert_point()
if num:
num = int(num)
if var1.get() == 0:
randomResult(people_list2,num)
else:
randomResult(people_list,num)
confirmBt['state'] = NORMAL
startBt['state'] = DISABLED
else:
is_run = False
showinfo('提示', '请输入抽奖人数!')
随机抽奖
def randomResult(list,num):
global is_run,i
global luck_people_list1, luck_people_list2
global people_dict,people_list,people_list2,people_list3
if len(list) <= num:
result = list
else:
result = random.sample(list, num)
result_name = []
for index,data in enumerate(result):
result_name.append(people_dict[data]['name'])
result_name_str = ','.join(result_name)
var_result.set(result_name_str)
if is_run:
window.after(10, randomResult, list, num)
#如果复位按钮被多次点击将会从指定名单中抽取
else:
if i > 0 and i < 10:
try:
result[0] = people_list3[0]
print(i)
i = 0
people_list3.pop(0)
result_name = []
for index, data in enumerate(result):
result_name.append(people_dict[data]['name'])
result_name_str = ','.join(result_name)
var_result.set(result_name_str)
except:
pass
else:
i = 0
print(result_name)
# print(var_result.get())
if var1.get() == 0:
for data in result:
try:
people_list2.remove(data)
except:
pass
luck_people_list2.append(result)
else:
luck_people_list1.append(result)
下面是一些按钮的事件
i = 0
is_run = False
def insert_point():
var = input.get() #获取输入的信息
return var
def finalResult():
global is_run
is_run = False
startBt['state'] = NORMAL
exportBt['state'] = NORMAL
resetBt['state'] = NORMAL
confirmBt['state'] = DISABLED
def reset():
result_name = "即将开始!"
var_result.set(result_name)
def onLeft(event):
global i
i=0
def Double_click(envent):
global i
i += 1
result_name = "即将开始!{}".format(i)
print(result_name)
def exportResult():
global luck_people_list1, luck_people_list2
global people_dict
luck_people_dict1 = []
luck_people_dict2 = []
for index,data in enumerate(luck_people_list1):
for luck in data:
dict1 = copy.deepcopy(people_dict[luck])
dict1['luck'] = index+1
luck_people_dict1.append(dict1)
for index,data in enumerate(luck_people_list2):
for luck in data:
dict1 = copy.deepcopy(people_dict[luck])
dict1['luck'] = index+1
luck_people_dict2.append(dict1)
# 获取今天的字符串
nowTime = time.strftime("%Y%m%d_%H%M%S", time.localtime(time.time()))
wb_readcsv.to_csv(os.path.dirname(os.path.realpath(sys.argv[0]))+"/可重复_{}.csv".format(nowTime),luck_people_dict1)
wb_readcsv.to_csv(os.path.dirname(os.path.realpath(sys.argv[0]))+"/不重复_{}.csv".format(nowTime), luck_people_dict2)
showinfo('提示', '导出完成!')
到这里,就完成了一个滚动抽奖的小程序,团建用起来,可以控制你想要的人唱歌…