团队聚会,难免抽奖环节,这里就需要一个抽奖小程序,于是花2个小时用tkinter快速实现了一个比较灵活实用的小程序。
程序已打包好如图1,peopleList.csv 是参与抽奖名单。
运行程序,双击lucky_Gift.exe 如图2
在小窗口中可以设置抽奖人数,是否允许重复抽取,同时抽动过程中可以让名单滚动起来如图3,可以导出抽奖记录csv格式,默认以导出时间命名。
这里面有个细节,python 读取csv 用pandas 很方便,但是打包成exe就头疼了,就为了读个csv让打包后的程序大了好几倍,不划算,于是自己实现了一个读取和写csv的函数。大大提高了程序运行效率。
读取csv代码如下:
# -*- 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' #“\ufeff”解决Excel 打开不乱码
s = s + line1
lineX = ','.join(dict1.values()) + '\n'
s = s + lineX
file.write(s)
except Exception as e:
print(e)