一 代码
#!/usr/bin/python# -*- coding: utf-8 -*-import timefrom tkinter import*# 配置# 要打开的图像image1 ="open.png"# 初始坐标x0 =50.0y0 =50.0# 列表将包含所有的x和y坐标.到目前为止,他们只包含初始坐标x =[x0]y =[y0]# 每次移动的速度或距离vx =1.0# x 速度vy =0.5# y 速度# 边界,这里要考虑到图片的大小,要预留一半的长和宽x_min =46.0y_min =46.0x_max =754.0y_max =554.0# 图片间隔时间,要动画效果,此处设为每秒40帧sleep_time =0.025# 运行步数range_min =1range_max =2000# 创建500次的x和y坐标for t in range(range_min,range_max):# 新坐标等于旧坐标加每次移动的距离new_x = x[t-1]+ vxnew_y = y[t-1]+ vy# 如果已经越过边界,反转方向if new_x >= x_max or new_x <= x_min:vx = vx*-1.0if new_y >= y_max or new_y <= y_min:vy = vy*-1.0# 添加新的值到列表x.append(new_x)y.append(new_y)# 开始使用tk绘图root =Tk()canvas =Canvas(width=800, height=600, bg='white')canvas.pack()photo1 =PhotoImage(file = image1)width1 = photo1.width()height1 = photo1.height()image_x =(width1)/2.0image_y =(height1)/2.0# 每次的移动for t in range(range_min,range_max):canvas.create_image(x[t], y[t], image = photo1,tag ="pic")canvas.update()# 暂停0.05妙,然后删除图像time.sleep(sleep_time)canvas.delete("pic")root.mainloop()
二 运行结果