小程序实现从name.xls 随机抽取指定数量的姓名,滚动显示在界面上,在按下抽奖后,确定中奖名单,并从name.xls中删除中奖人员
# -*- coding: utf-8 -*-
import os
import tkinter
from tkinter.font import Font
from PIL import Image, ImageTk
import _thread as thread, time
import xlrd
import xlwt
import random
excel_file = './name.xls' # 未中奖名单
bg_file = './bg.jpg' # 背景图
is_change: bool = False
def get_name_list_from_excel(file_name):
""""解析 file_name 文件,得到人员名单列表\""""
return_list = []
read_file = xlrd.open_workbook(file_name)
sheet = read_file.sheet_by_name('Sheet1')
for row in range(1, sheet.nrows):
job_name = sheet.cell(row, 0).value
return_list.append(job_name)
return return_list
def set_name_list_to_excel(file_name, lists):
""""写入人员名单列表\""""
write_file = xlwt.Workbook()
# 创建一个worksheet
worksheet = write_file.add_sheet('Sheet1')
# 写入excel
# 参数对应 行, 列, 值
worksheet.write(0, 0, "姓名")
for row in range(0, len(lists)):
worksheet.write(row + 1, 0, label=lists[row])
# 保存
write_file.save(file_name)
def running():
""""抽奖线程\""""
global is_change
is_run = False
while len(name_list):
if is_change:
# 按键有按下
is_change = False
if is_run: # 停止抽奖
is_run = False
for count in range(0, len(lucky_list)):
name_list.remove(lucky_list[count])
if os.path.exists(excel_file): # 删除原有的excel文件
os.remove(excel_file)
set_name_list_to_excel(excel_file, name_list) # 创建新的未中奖名单
else: # 开始抽奖
is_run = True
if is_run:
# 在抽奖中,循环显示名单
lucky_str = ''
lucky_list.clear()
name_list_temp = name_list[:] # 临时名单,防止显示多个时抽到同名
for count in range(0, int(name_num.get())):
index = random.randint(0, len(name_list_temp) - 1)
lucky_list.append(name_list_temp[index])
name_list_temp.remove(name_list_temp[index])
for count in range(0, len(lucky_list)): # 显示名单
lucky_str1 = lucky_list[count]
if len(lucky_str1) == 2:
lucky_str1 = lucky_str1[0] + " " + lucky_str1[1]
lucky_str += lucky_str1 + " "
if (count + 1) % 4 == 0:
lucky_str += "\n"
print(lucky_str)
lucky_name.set(lucky_str)
time.sleep(0.05) # 循环时间,影响姓名滚动的速度
# new_list.remove(new_list[index])
root = tkinter.Tk()
root.geometry("1280x720") # 设置窗口尺寸
# 说明图片位置,并导入图片到画布上
img = ImageTk.PhotoImage(file=bg_file)
name_num = tkinter.StringVar() # 一次抽多少个
name_num.set('1')
lucky_name = tkinter.StringVar() # 显示滚动的姓名
lucky_name.set('')
labelName = tkinter.Label(root, textvariable=lucky_name, fg='red', compound=tkinter.CENTER, font=Font(size=60),
image=img)
labelName.place(relx=0.5, rely=0.2, anchor=tkinter.CENTER)
entryName = tkinter.Entry(root, width=2, font=Font(size=30), textvariable=name_num)
entryName.place(relx=0.6, rely=0.8, anchor=tkinter.CENTER)
name_list = get_name_list_from_excel(excel_file)
lucky_list = [] # 保存抽中的姓名列表
def lucky_go():
global is_change
is_change = True
thread.start_new_thread(running, ())
button_lucky = tkinter.Button(root, text='抽奖', command=lucky_go, font=Font(size=30))
button_lucky.place(relx=0.5, rely=0.8, anchor=tkinter.CENTER)
root.mainloop()