专业视觉设计师,5年b端产品经理职业生涯,最近痴迷于编程,追求全栈工程师,厚积薄发。励志一个月玩转python GUI。记录下自学过程,纯属单纯的喜欢编程,与大家分享。 先来个简单的canvas动画:桌面弹力球 源码: import tkinter import random root=tkinter.Tk() root.title(“envent”) root.geometry(“400x300+10+10”) hb=tkinter.Canvas(root,width=400,height=300,bg="#189fff") hb.pack() oval = hb.create_oval(0, 0,16,16, fill=“red”,outline="") pzzt=[0,1,1]#状态(0,1,2,3)如下,随机移动x,随机移动y def callback(canvas=hb,canvas_w=400,canvas_h=300,r=10,state=pzzt): zb = canvas.bbox(oval) #获取小球坐标 #—条件----------------------- if zb[2]>=canvas_w or (zb[2]==canvas_w and zb[3]==r):#撞击右边-修改状态向左 or 撞击NE ;修改状态,向SW state[0]=1 state[1] = random.randint(1,2) state[2] = random.randint(1,2) elif zb[0]<=0 or (zb[0]==0 and zb[2]==canvas_h-r):#撞击左边-修改状态向右 or 撞击SW ;修改状态,向NE state[0]=0 state[1] = random.randint(1,3) state[2] = random.randint(3,6) elif zb[1]<=0 or (zb[0]==0 and zb[1]==0):#撞击上边-修改状态向下 or 撞击NW ;修改状态,向SE state[0] = 2 state[1] = random.randint(3,6) state[2] = random.randint(1,3) elif zb[3]>=canvas_h or (zb[2]==canvas_w and zb[3]==canvas_h):#撞击下边-修改状态向上 or 撞击SE ;修改状态,向NW state[0] = 3 state[1] = random.randint(1,5) state[2] = random.randint(10,20) # —运动----------------------- if state[0]==0: canvas.move(oval,state[1],-state[2]) #向右、向上、或指向NE —正负 elif state[0]==1: canvas.move(oval,-state[1],state[2]) #向左、向下、向SW —负正 elif state[0]==2: canvas.move(oval,state[1],state[2]) #向下、向右、指向SE —正正 elif state[0]==3: canvas.move(oval,-state[1],-state[2]) #向上、向左、指向NW —负负 canvas.after(30,callback) callback() root.mainloop()
|