""" tkinter星光旋转.py 面向对象编程案例, 本程序适合于初三以上学习过三角函数的学生学习, 作者: 李兴球 2022/9/16 """ import time import math import random from tkinter import * class Vector2D(tuple): """2D向量类""" def __new__(cls, x, y): return tuple.__new__(cls, (x, y)) def __sub__(self, other): return Vec2D(self[0]-other[0], self[1]-other[1]) def rotate(self,angle=1): perp = Vector2D(-self[1], self[0]) angle = angle * math.pi / 180.0 c, s = math.cos(angle), math.sin(angle) return Vector2D(self[0]*c+perp[0]*s, self[1]*c+perp[1]*s) class Point: # 表示一个点的类 def __init__(self,x,y,canvas): self.x = x self.y = y self.cv = canvas # 创建一个'实体'点 self.item = cv.create_oval(x,y,x+1,y+1,fill='white') def rotate(self,center=(0,0),degree=-1): x1,y1,x2,y2 = self.cv.coords(self.item) points = [(x1,y1),(x2,y2)] points= [Vector2D(x,y) for x,y in points] # 转换为向量 points = [C-center for C in points] points = [C.rotate(degree) for C in points] points = [C+center for C in points] points = [points[0][0],points[0][1],points[1][0],points[1][1]] self.cv.coords(self.item,points) if __name__ == '__main__': root = Tk() cv = Canvas(root,bg='black',width=800,height=800) cv.pack() # 创建2000个点 points = [(random.randint(-800,800),random.randint(-800,800)) for i in range(2000)] dots = [Point(x,y,cv) for x,y in points] # 实例化2000个点 while True: [d.rotate() for d in dots] cv.update()
李兴球
李兴球的博客是Python创意编程原创博客
要发表评论,您必须先登录。
发表评论