为了上课时间能够随机抽点学生,就利用Python做了这个随机点名系统
实现的功能会读取文件里内第一个格式为.xlsx的文件,如果该文件里面有姓名,学号两列数据就能够正常运行,注意列名必须为姓名,学号。如果点名的时间想放音乐,在文件夹内部放入mp3即可,需要将mp3名修改为"点名.mp3"
目前存在问题是启动速度慢,不知道如何解决,存疑,后面解决了再改
import os
import tkinter as tk
import tkinter as Tkinter
from tkinter import *
import tkinter.messagebox
import random
import pandas as pd
import pygame
from pandas import DataFrame
path = "./"
files = os.listdir()
#print(len(files))
for i in range(0, len(files)):
try:
filetype = files[i].split(".")[1]
if filetype == "xls" or filetype == "xlsx":
filedata = files[i]
break
except:
print("有文件没有表明文件类型")
else:
pass
test1 = pd.read_excel(filedata)
data3 = test1["姓名"]
data4 = test1["学号"]
data1 = []
data2 = []
data1[0:] = data4[1:]
data2[0:] = data3[1:]
#print(type(data))
going = True # 表示是否可以继续滚动(递归)显示下一个名额
is_run = False # 表示当前抽奖器是否在运行
# def lottery_roll(var1, var2):
def lottery_roll(var1):
global going
show_member1 = random.choice(data1) # 随机选取姓名
show_member2 = random.choice(data2)
#DataFrame.sample(1)
#print(type(show_member))
show_member = [int(show_member1),show_member2]
var1.set(show_member) # var1 显示抽取出来的姓名
if going: # going=True
window.after(50, lottery_roll, var1) # 每50毫秒循环一次
else: # going=False
#result = tkinter.messagebox.showinfo(title='最终结果!', message='恭喜 {} !!!'.format(show_member)) # 弹窗显示恭喜+抽取出来的姓名
going = True
return # 跳出def
def lottery_start(var1):
pygame.mixer.init()
try:
pygame.mixer.music.load(r"./点名.mp3") # 路径
except:
pass
global is_run
if is_run: # is_run = True
return # 跳出def
is_run = True
lottery_roll(var1) # 执行循环抽取姓名的执行语句
pygame.mixer.music.play(loops=4) #音乐开始 pygame.mixer.music.play(loops,start) loops是循环播放,start是开始位置(0-1)
pygame.mixer.music.set_volume(0.7) #控制音乐声音的大小
def lottery_end():
global going, is_run
if is_run:
going = False
is_run = False
pygame.mixer.music.stop()
if __name__ == '__main__': # 如果模块是被直接运行的,则代码块被运行,如果模块是被导入的,则代码块不被运行。
window = Tkinter.Tk()
window.title('点名V1.0')
window.geometry('450x320')
#window.geometry('450x320+250+15')
# bg_label = Label(window, width=70, height=24, bg='#ECf5FF')
bg_label = Label(window, width=70, height=24)
bg_label.place(anchor=NW, x=0, y=0)
var1 = StringVar(value='谁会是天选之子')
#show_label1 = Label(window, textvariable=var1, justify='left', anchor=CENTER, width=17, height=3, bg='#BFEFFF',
# font='楷体 -40 bold', foreground='black')
show_label1 = Label(window, textvariable=var1, justify='left', anchor=CENTER, width=17, height=3,
font='华文行楷 -40 bold', foreground='black')
show_label1.place(anchor=NW, x=30, y=20)
button1 = Button(window, text='开始', command=lambda: lottery_start(var1), width=14, height=2, bg='#A8A8A8',
font='华文仿宋 -18 bold')
button1.place(anchor=NW, x=32, y=175)
button2 = Button(window, text='结束', command=lambda: lottery_end(), width=14, height=2, bg='#A8A8A8',
font='华文隶书 -18 bold')
button2.place(anchor=NW, x=232, y=175)
window.mainloop()
代码写完后,实验pyinstaller -F -w命令将程序打包即可
运行效果如下