先创建图片文件夹,图片名就是用户名
from tkinter import *
from PIL import Image, ImageTk
import time,random,os
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):
self.label = Label(self, textvariable=self.timestr, font=("思源宋体", 45), pady=50)
self.label.pack(side=TOP)
self.image_label = Label(self)
self.image_label.pack()
self.set_name(self._elapsedtime)
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))
# 从用户列表随机一个
cur = random.randint(0, len(name_list) - 1)
username = name_list[cur]
image_path = os.path.join(images_folder, username + ".png")
self.timestr.set(username)
# 设置图片
image = Image.open(image_path)
image = image.resize((200, 200))
photo = ImageTk.PhotoImage(image)
self.image_label.configure(image=photo)
self.image_label.image = photo
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)
# 图片文件夹
images_folder = "./students"
# 把用户名抽出来
name_list = [os.path.splitext(img)[0] for img in os.listdir(images_folder) if img.endswith('.png')]
if __name__ == '__main__':
root = Tk()
root.title("随机点名")
root.geometry('400x500')
root.resizable(0, 0)
sw = RandomName(root)
sw.name_label()
root.mainloop()
标签:__,点名,name,python,self,label,随机,._,image
From: https://www.cnblogs.com/qcy-blog/p/18152193