# -*- encoding:Utf8 -*-

from tkinter import *
from random import *
from math import *

#==== Classe secondaire ====

class Fleur(object):
    
    def __init__(self, canevas, x, y, r):
        """
        Crée une fleur de rayon r centrée au point de coordonnées (x;y)
        dans le canevas <can>
        """
        # création des pétales blancs:
        alpha = 0
        while alpha < 2*pi:
            canevas.create_oval(x+r*cos(alpha)-r/1.5, y - r*sin(alpha)-r/1.5,\
                            x+r*cos(alpha)+r/1.5, y - r*sin(alpha)+r/1.5,\
                            fill = 'white')
            alpha += pi/4

        # création du bouton jaune:
        canevas.create_oval(x-r, y-r, x+r, y+r, fill = 'yellow')

#==== Classe principale ====

class Application(Tk):

    def __init__(self):
        Tk.__init__(self)
        self.title("Exercice 8.10")

        # Création et positionnement des étiquettes de texte:
        Label(self, text = "V'là le printemps !", fg='blue', width=18,
              bg='pink', font = ("Comic sans Ms", "22")).grid(row = 1, column = 5, columnspan = 2, pady=5)

        Label(self, text = 'Coord. x : ', fg='blue',
              font=("Comic sans Ms", "16")).grid(row = 2, column = 1, sticky = W)
        Label(self, text = 'Coord. y : ', fg='blue',
              font=("Comic sans Ms", "16")).grid(row = 3, column = 1, sticky = W)
        Label(self, text = 'Insecte : ', fg='blue',
              font=("Comic sans Ms", "16")).grid(row = 4, column = 1, rowspan = 2, sticky = W)

        # Création et positionnement des zones de texte:
        self.coordx = Entry(self, width = 22)
        self.coordy = Entry(self, width = 22)
        self.coordx.grid(row = 2, column = 2, sticky = E)
        self.coordy.grid(row = 3, column = 2, sticky = E)

        # Dictionnaire des images affichables:
        self.imgInsecte = {'abeille': PhotoImage(file = 'abeille.gif'),
                           'coccinelle': PhotoImage(file = 'coccinelle.gif'),
                           'papillon': PhotoImage(file = 'papillon.gif')}
        # Insecte actuellement prêt à être affiché:
        self.insecte = 'abeille'

        # Création et positionnement de la liste de choix:
        self.liste = Listbox(self, height = 3, width = 20, bg='yellow')
        self.liste.grid(row = 4, column = 2, rowspan = 2)
        for animal in ['abeille', 'coccinelle', 'papillon']:
            self.liste.insert(END, animal)

        # Un double click dans la liste appelle le gestionnaire d'événement choixInsecte:
        self.liste.bind('<Double-1>', self.choixInsecte)

        # Création et positionnement du canvas:
        self.can = Canvas(self, width = 400, height = 200, bg = 'lightgreen')
        self.can.grid(row = 2, column = 3, rowspan = 4, columnspan = 6, padx = 10, pady = 5)

        # Création et positionnement des boutons (Utilisation d'un code compact)
        Button(self, text='Insecte', command=self.afficherInsecte).grid(row = 7, column = 4, pady=5)
        Button(self, text='Fleurs', command=self.afficheFleurs).grid(row = 7, column = 5)
        Button(self, text='Effacer', command=self.effacerCanevas).grid(row = 7, column = 6)
        Button(self, text='Quitter', command=self.quit).grid(row = 7, column = 7)

        
    def afficheFleurs(self):
        """
        Affiche 15 fleurs de différents rayons de manière aléatoire dans le canevas
        """
        for i in range(15):
            x = randint(15, self.can.winfo_width()-15)
            y = randint(15, self.can.winfo_height()-15)
            r = randint(4,10)
            Fleur(self.can, x, y, r)

    def effacerCanevas(self):
        "Efface l'ensemble des éléments situés sur le canevas <can>"
        self.can.delete(ALL)

    def choixInsecte(self, event):
        "Mise à jour de l'insecte à afficher"
        self.insecte = self.liste.get(self.liste.curselection())

    def afficherInsecte(self):
        """
        Affiche l'insecte à la position indiquée dans les champs de texte
        ou à une position aléatoire si l'utilisateur n'a pas rempli les champs.
        """
        if self.coordx.get() == "" or self.coordy.get() == "":
            x = randint(25, self.can.winfo_width()-25)          # winfo_width permet de récupérer la largeur d'un canevas
            y = randint(25, self.can.winfo_height()-25)         # winfo_height permet de récupérer la hauteur d'un canevas

        else:
            x = int(self.coordx.get())
            y = int(self.coordy.get())

        self.coordx.delete(0, END)
        self.coordy.delete(0, END)

        # affichage de l'insecte sélectionné dans la variable self.insecte:
        self.can.create_image(x, y, image = self.imgInsecte[self.insecte])


#==== Corps principal du programme ====

# Création du widget principal:
fen = Application()

# Démarrage du réceptionneur d'événements
fen.mainloop()
fen.destroy()
