首先附上源代码
import tkinter as tk
import random
import threading
import time
from PIL import Image,ImageTk
import re
import os
#初始化窗口
def switch(): #随机数生成
root.flag=True
while root.flag:
i=random.randint(0, len(a)-1)
s=a[i]
s=re.split(' |\n',s)
image_file['file']=ps[i]
name['text']=s[0] #将s列表被切割后的第一个列表赋给name的text
code['text']=s[1]
time.sleep(0.5)
def butStartClick(): #开始
t=threading.Thread(target=switch) #多线程操作
t.start()
def btnStopClick(): #结束
root.flag=False
def main():
global root
global students,name,code,image_file,ps,a
root=tk.Tk()
root.title("随机名单")
root.geometry('500x500+500+100')#+后面为窗口位置
root.resizable(False,False)
root.flag = True
canvas=tk.Canvas(root,width=500,height=500,bd=1,highlightthickness=0)
image_file=tk.PhotoImage(file='ps4.gif')
image=canvas.create_image(150,0,anchor='n',image=image_file) #anchor为锚点,放置在北
canvas.pack()
ps=['ps1.gif','ps2.gif','ps3.gif','ps4.gif','ps5.gif','ps6.gif'] #已准备好的gif图片,并且在同一目录下
name = tk.Label(root,text='某某某',font = ("华文行楷", 30,"normal"))
name.place(x=320,y=150,width=150,height=100)
code = tk.Label(root,text='xxx',font = ("宋体", 20,"normal"))
code['fg'] = 'red'
code.place(x=320,y=250,width=150,height=50)
os.chdir(r'C:\python专用') #读取以下目录
with open("花名册.txt",'r',encoding='utf-8') as file: #打开文件txt
a=file.readlines()
btnStart=tk.Button(root,text='开始',command=butStartClick)
btnStart.place(x=360, y=360, width=80, height=40)
butStop=tk.Button(root,text='停止',command=btnStopClick)
butStop.place(x=360, y=400, width=80, height=40)
root.mainloop()
if __name__ == '__main__' :
main()
txt文档格式
图片建议用ps转为GIF格式,其他格式的话,图片展示需要调用其他函数
最后实现如下
视频在此