通过读取学生txt,进而实现随机选人(包含对应人物照片)并用GUI实现

首先附上源代码

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文档格式
在这里插入图片描述
ps1在这里插入图片描述图片建议用ps转为GIF格式,其他格式的话,图片展示需要调用其他函数

最后实现如下
视频在此
在这里插入图片描述

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值