1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| #!/usr/bin/env python
#coding=utf-8
from Tkinter import *
# définition des gestionnaires
# d'événements :
def move():
global x1, y1, dx, dy, flag,coul
x1, y1 = x1 +dx, y1 + dy
if x1 >210:
changecolour()
x1, dx, dy = 210, 0, 15
elif y1 >210:
changecolour()
y1, dx, dy = 210, -15, 0
elif x1 <10:
changecolour()
x1, dx, dy = 10, 0, -15
elif y1 <10:
changecolour()
y1, dx, dy = 10, 15, 0
can1.coords(oval1,x1,y1,x1+30,y1+30)
if flag >0:
fen1.after(50,move) # => boucler après 50 milliseconde
def stop_it():
global flag
flag =0
def start_it():
global flag
if flag ==0: # pour ne lancer qu'une seule boucle
flag = 1
move()
def changecolour():
if x1>210:
can1.itemconfigure(oval1, fill= 'red')
elif y1>210:
can1.itemconfigure(oval1, fill= 'blue')
elif x1<10:
can1.itemconfigure(oval1, fill= 'yellow')
elif y1<10:
can1.itemconfigure(oval1, fill= 'black')
#========== Programme principal =============
# les variables suivantes seront utilisées de manière globale :
x1, y1 = 10, 10 # coordonnées initiales
dx, dy = 15, 0 # 'pas' du déplacement
flag =0 # commutateur
# Création du widget principal ("parent") :
fen1 = Tk()
fen1.title("Exercice d'animation avec Tkinter")
# création des widgets "enfants" :
can1 = Canvas(fen1,bg='dark grey',height=250, width=250)
can1.pack(side=LEFT, padx =5, pady =5)
oval1 = can1.create_oval(x1, y1, x1+30, y1+30, width=2,fill = 'red')
bou1 = Button(fen1,text='Quitter', width =8, command=fen1.quit)
bou1.pack(side=BOTTOM)
bou2 = Button(fen1, text='Démarrer', width =8, command=start_it)
bou2.pack()
bou3 = Button(fen1, text='Arrêter', width =8, command=stop_it)
bou3.pack()
# démarrage du réceptionnaire d'évènements (boucle principale) :
fen1.mainloop() |
Partager