简介
无意间翻出3年前制作的一款随机图片小工具,可以用于抽奖、点名等场景,话不多说直接上代码
代码实现
#! encoding=utf-8
import tkinter
import random
import threading
import time
import os
from PIL import Image, ImageTk
import tkinter.filedialog
# 初始化窗口
root = tkinter.Tk()
root.title("随机名单")
root.geometry('400x500+400+200')
root.resizable(False, False)
root.flag = True
root.resizable(0, 0)
def people():
global students,filename
students = []
tk = tkinter.Tk() # 新建窗体
tk.withdraw() # 消除弹窗
filename = tkinter.filedialog.askdirectory()
for i in os.listdir(filename):
print(i)
students.append(i)
btn = tkinter.Button(root, text='选择人员', command=people)
btn.place(x=120, y=30, width=80, height=20)
# 三个Lable标签
photo = tkinter.Label(root)
photo.place(x=50, y=50, width=300, height=400)
third = tkinter.Label(root, text='', font=("宋体", 20, "normal"))
third.place(x=50, y=400, width=300, height=100)
def switch():
root.flag = True
global photo, tk_image
while root.flag:
i = random.randint(0, len(students) - 1)
im = Image.open(filename+'/'+students[i])
(x, y) = im.size
x_s = 300
y_s = int(y * x_s / x)
out = im.resize((x_s, y_s), Image.ANTIALIAS)
# out = out.rotate(90) #向右旋转90度
pil_image = out
tk_image = ImageTk.PhotoImage(pil_image)
third['text'] = students[i].split('.')[0]
time.sleep(0.2)
photo.configure(image=tk_image)
# 开始按钮
def butStartClick():
t = threading.Thread(target=switch)
t.start()
btnStart = tkinter.Button(root, text='开始', command=butStartClick)
btnStart.place(x=30, y=30, width=80, height=20)
# 结束按钮
def btnStopClick():
root.flag = False
butStop = tkinter.Button(root, text='停止', command=btnStopClick)
butStop.place(x=220, y=30, width=80, height=20)
def closeWindow():
root.destroy()
exit()
return
root.protocol('WM_DELETE_WINDOW', closeWindow)
# 启动主程序
root.mainloop()
说明
以上代码运行后,先点击选择人员按钮,选择一个只有图片(jpg)的文件夹,点击开始后,进行随机显示,点击停止,即可暂停,底下显示的姓名为图片名称。
运行图片