#! /usr/bin/env python
# -*- coding:Utf8 -*-

# Animation automatique d'une balle

from tkinter import *

class Application(Tk):

    def __init__(self):
        # Création du widget principal
        Tk.__init__(self)
        self.title("Exercice d'animation avec tkinter")

        # Coordonnées initiales de position de la balle:
        self.x, self.y = 10, 10

        # 'Pas' du déplacement de la balle:
        self.dx, self.dy = 15, 0

        # Commutateur:
        self.flag=0

        # Création des widgets "esclaves":
        self.can = Canvas(self, bg = "dark grey", height=250, width=250)
        self.balle = self.can.create_oval(self.x, self.y, self.x+30, self.y+30,
                                    width=2, fill='red')
        self.can.pack(side=LEFT)
        Button(self,text='Quitter',command=self.destroy).pack(side=BOTTOM)
        Button(self,text='Démarrer',
               command=self.start_it).pack()
        Button(self,text='Arrêter',
               command=self.stop_it).pack()

    def move(self):
        "déplacement de la balle"

        self.x, self.y = self.x+self.dx, self.y+self.dy

        if self.x >210:
            self.x, self.dx, self.dy = 210, 0, 15
        if self.y >210:
            self.y, self.dx, self.dy = 210, -15, 0
        if self.x <10:
            self.x, self.dx, self.dy = 10, 0, -15
        if self.y <10:
            self.y, self.dx, self.dy = 10, 15, 0
        self.can.coords(self.balle,self.x,self.y,self.x+30,self.y+30)
        if self.flag >0: 
            self.after(50,self.move)	    # boucler après 50 millisecondes


    def stop_it(self):
        "arret de l'animation"   
        self.flag =0

    def start_it(self):
        "démarrage de l'animation"
        if self.flag ==0:	# pour éviter que le bouton ne puisse lancer plusieurs boucles 
           self.flag =1
           self.move()


#------ Programme principal -------

Application().mainloop()
