今天七夕,还下着雨,刚好想做一个下着爱心雨的特效
准备图片素材
1、美图秀秀找一个爱心图,大小就50*50就可以,生成的是一个png格式文件
2、由于canvas.create_image只支持gif图片,所以在线转换一下,我这里用的是我拉网:http://pic.55.la/
创建画布,画布添加爱心图,图片下落,使用多线程(由于雨要一直下)
Python好难写,调试了半天,话不多说,看看小白初步实现的代码,关键地方加了注释
#-*- coding:utf-8 -*-#__author__ :kusy#__content__:文件说明#__date__:2018/8/17 9:28
from tkinter import *
importrandomimportthreadingimporttimeimportos#初始雨滴纵坐标
INIT_HEIGHT = 10
#雨滴创建
defrainmake(canvas,imagefile):
rainlist=[]for i in range(10):#根据图片,创建一排心
rainlist.append(canvas.create_image(100 + 80 * i, INIT_HEIGHT, anchor=NE, image=imagefile))returnrainlist#雨滴下落
defraindown(tk,canvas,imagefile,sec):#线程间等待
time.sleep(sec)
rainlist=rainmake(canvas,imagefile)#每颗心的纵坐标值
height = [INIT_HEIGHT] * 10
whileTrue:#每次移动前稍等一会
time.sleep(0.2)#10颗心一起移动
for i in range(10):#如果这颗心到底了,则不继续移动,否则height重置就无效了
if not height[i] ==0:#设置下落步调
rnd = random.randint(5,50)
canvas.move(rainlist[i],0,rnd)
height[i]= height[i] +rnd
tk.update()for i,h inenumerate(height):if h > 600:#当这颗心走到最下方,则删除
canvas.delete(rainlist[i])
tk.update()#清空这颗心的height
height[i] =0print(i,h,height)#10颗心全到底,则跳出循环
#print(height,height == [0] * 10)
if height == [0] * 10:print('break:',threading.current_thread().name)break
deflookloop(tk,canvas,thread):
aliveflg=FalsewhileTrue:#5s检测一次
time.sleep(5)for th inthread:ifth.is_alive():
aliveflg=Trueelse:
aliveflg=Falseif aliveflg ==False:break
#Over
canvas.create_text(200,300,text='不好意思,雨停了...',fill='red')
canvas.pack()
time.sleep(5)
tk.destroy()defmain():#创建窗口对象
tk =Tk()
tk.title('七夕之雨')
canvas_style={'bg':'white','height':'700','width':'900','cursor':'circle'}#创建画布
canvas =Canvas(tk,canvas_style)
canvas.pack()#图片素材
if not os.path.exists('7777777.gif'):raise Exception('7777777.gif file does not exists.')
imagefile= PhotoImage(file = "7777777.gif")
thread=[]for i in range(10):
thread.append(threading.Thread(target=raindown,args=(tk,canvas,imagefile,i)))for t inthread:
t.start()#新开一个线程监控运行中的10个线程
threading.Thread(target=lookloop,args=(tk,canvas,thread)).start()#进入消息循环
tk.mainloop()if __name__ == '__main__':
main()
动态效果图如下
最重要的一步:发给妹子
(当然要发给妹子,不然做这个干啥)可以打包成exe文件,和素材图片一起发给妹子。。。
我的博客即将搬运同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=1ntsxvl0xbssw