两个球


               
               
                from Tkinter import *
from math import sin, cos, pi
WIDTH = 300
HEIGHT = 300
BALL_RADIUS = 30      #
FRAMES_PER_SEC = 200   #
w=0.4                  #
ball_time=0           #
def main():
    global ball_time
    initialise()
    mainloop()
def initialise():
    build_balls()
    build_graph()
def build_balls():
    # Create balls variable.
    global balls
    balls = (Ball(0,0,'red'),Ball(2*BALL_RADIUS,0,'green'))
def build_graph():
    # Build GUI environment.
    global graph
    root = Tk()
    root.title('Coins')
    graph = Canvas(root, width=WIDTH, height=HEIGHT, background='white')
    graph.after(1000 / FRAMES_PER_SEC, update)
    graph.pack()
def update():
    graph.after(1000 / FRAMES_PER_SEC, update)
    balls[1].roll()
    draw()
def draw():
    #
    graph.delete(ALL)
    for ball in balls:
        x1 = ball.x - BALL_RADIUS
        y1 = ball.y - BALL_RADIUS
        x2 = ball.x + BALL_RADIUS
        y2 = ball.y + BALL_RADIUS
        graph.create_oval((x1, y1, x2, y2), fill=ball.color)
        graph.create_line(ball.four_points[:4], fill='yellow', width=0.5)
        graph.create_line(ball.four_points[4:], fill='yellow', width=0.5)
    graph.update()
################################################################################
class Ball:
    def __init__(self,x,y,color):
        xx = x+WIDTH/2
        yy= y+HEIGHT/2
        self.x=xx
        self.y=yy
        self.color=color
        self.four_points=(xx-BALL_RADIUS,yy,xx+BALL_RADIUS,yy,xx,yy+BALL_RADIUS,xx,yy-BALL_RADIUS)
    def roll(self):
        global ball_time
        t=ball_time
        w2=2*w
        xx,yy=2*BALL_RADIUS*cos(w*t),2*BALL_RADIUS*sin(w*t)
        xxx,yyy=BALL_RADIUS*cos(w2*t),BALL_RADIUS*sin(w2*t)
        l_x,l_y=xx-xxx,yy-yyy
        r_x,r_y=xx+xxx,yy+yyy
        u_x,u_y=xx+yyy,yy-xxx
        d_x,d_y=xx-yyy,yy+xxx
        self.x,self.y=xx+WIDTH/2,yy+HEIGHT/2
        self.four_points=(l_x+WIDTH/2,l_y+HEIGHT/2,r_x+WIDTH/2,\
                          r_y+HEIGHT/2,u_x+WIDTH/2,u_y+HEIGHT/2,d_x+WIDTH/2,d_y+HEIGHT/2)
        ball_time += 0.1
################################################################################
# Execute the simulation.
if __name__ == '__main__':
    main()