一、需求:
教师上课常用的点名软件
二、python库安装:
openpyxl是Python中用于读写excel文件
tkinter是Python中GUI编程非常好用的库,而且是标准库,不需要安装,导入即可使用
random库是Python中用于实现随机功能的库,也是Python的标准库,不需要安装,导入即可使用
pyinstaller库是Python打包成exe所需要用到的
pip install openpyxl
pip install pyinstaller
三、代码:
import tkinter as tk
from tkinter import *
import random
import time
import openpyxl
is_run = False
def get_students_name():
# 学生名单中需要有"姓名"列
workbook = openpyxl.load_workbook('学生名单.xlsx')
table = workbook.active
rows, cols = table.max_row, table.max_column
name_col = 0
for col in range(cols):
if table.cell(1, col + 1).value == '姓名':
name_col = col
break
students_name = [table.cell(row + 1, name_col + 1).value for row in range(1, rows)
if table.cell(row + 1, name_col + 1).value is not None]
return students_name
def call_lucky_student(var):
"""点名"""
global is_run
if is_run:
return
is_run = True
start = time.time()
choice_student(var, start)
def choice_student(var, start):
global is_run
show_member = random.choice(get_students_name())
name = show_member[0]
for zi in show_member[1:]:
name += ' ' + zi
var.set(name)
end = time.time()
if is_run and end - start <= 5:
window.after(30, choice_student, var, start)
else:
is_run = False
return
if __name__ == '__main__':
window = tk.Tk()
window.resizable(width=False, height=False)
window.geometry('600x400+400+180')
window.title('\t 学 生 点 名 系 统')
# 添加显示框
var = StringVar(value='公平 公正 公开')
show_label1 = Label(window, textvariable=var, justify='left', anchor=CENTER, width=16,
height=2, font='楷体 -40 bold', foreground='white', bg='#1C86EE')
show_label1.place(anchor=tk.NW, x=130, y=90)
# 添加点名按钮
button = Button(window, text='点 名', compound='center', font='楷体 -30 bold',
foreground='#9400D3',
command=lambda: call_lucky_student(var))
button.place(anchor=NW, x=235, y=200)
# 显示窗口
window.mainloop()
四、打包成exe文件
# ss为文件名,命令行与文件要在一个文件夹内
pyinstaller -F -w ss.py
把学生名单excel表格和软件放在同一个位置打开软件即可
注意:学生名单中需要有"姓名"列
五、效果: