新建txt文本,输入名字,每个进行换行
from tkinter import *
import time
class RandomName(Frame):
def __init__(self, parent=None, **kw):
Frame.__init__(self, parent, kw)
self._timer = None
self._start = 0.0
self._elapsedtime = 0.0
self._running = False
self.timestr = StringVar()
self.makeWidgets()
def makeWidgets(self):
# 定义标签栏
l = Label(self, textvariable=self.timestr, font=("思源宋体", 45), pady=50)
self.set_name(self._elapsedtime)
l.pack(side=TOP)
def update(self):
# 更新显示内容
self._elapsedtime = time.time() - self._start
self.set_name(self._elapsedtime) # 设置显示内容
self._timer = self.after(50, self.update) # 刷新界面
def set_name(self, elap):
# 随机产生姓名
cur = int(elap * 100 % len(name_list))
self.timestr.set(name_list[cur])
# 开始
def start(self):
if not self._running:
self._start = time.time() - self._elapsedtime
self.update()
self._running = True
# 暂停
def stop(self):
if self._running:
self.after_cancel(self._timer)
self._elapsedtime = time.time() - self._start
self.set_name(self._elapsedtime)
self._running = False
def name_label(self):
# 显示窗口
self.pack(side=TOP)
Button(self, text='开始', command=self.start, width=10, height=2, bg="SeaGreen", font=("思源宋体", 13)).pack(side=LEFT)
Button(self, text='结束', command=self.stop, width=10, height=2, bg="Red", font=("思源宋体", 13)).pack(side=LEFT)
name_list = []
if __name__ == '__main__':
# 读取学生txt文件
file_path = "./students.txt"
with open(file_path, "r", encoding="utf-8") as file:
content = file.read()
lines = content.split('\n')
for line in lines:
name_list.append(line)
root = Tk()
root.title("随机点名")
root.geometry('400x280')
root.resizable(0, 0)
sw = RandomName(root)
sw.name_label()
root.mainloop()
标签:__,点名,name,python,self,elapsedtime,随机,._,def
From: https://www.cnblogs.com/qcy-blog/p/18152087