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 68 69 70 71 72
| #-*-coding:utf-8-*-
from Tkinter import *
# définition des gestionnaires
# d'événements :
def move():
"déplacement de la balle"
global x1, y1, dx, dy, flag
x1, y1= x1 +dx, y1 + dy
if x1 >210:
x1, dx, dy = 210, -dx, dy
if y1 >210:
y1, dx, dy = 210, dx, -dy
if x1 <10:
x1, dx, dy = 10, -dx, dy
if y1 <10:
y1, dx, dy = 10, dx, -dy
can1.coords(oval1,x1,y1,x1+30,y1+30)
if flag >0:
fen1.after(50,move) # boucler après 50 millisecondes
def move2():
"déplacement de la balle"
global x2, y2, dt, dz, flag
x2, y2= x2 +dt, y2 + dz
if x2 >210:
x2, dt, dz = 210, -dt, dz
if y2 >210:
y2, dt, dz = 210, dt, -dz
if x2 <10:
x2, dt, dz = 10, -dt, dz
if y2 <10:
y2, dt, dz = 10, dt, -dz
can1.coords(oval2,x2,y2,x2+30,y2+30)
if flag >0:
fen1.after(50,move2) # boucler après 50 millisecondes
def stop_it():
"arret de l'animation"
global flag
flag =0
def start_it():
"démarrage de l'animation"
global flag
if flag ==0: # pour ne lancer qu'une seule boucle
flag =1
move()
move2()
#========== Programme principal =============
# les variables suivantes seront utilisées de manière globale :
x1, y1, x2, y2 = 10, 10, 210, 210 # coordonnées initiales
dx, dy = 15, 3 # 'pas' du déplacement 1
dt, dz = -15, -3
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='purple',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='white')
oval2 = can1.create_oval(x2, y2, x2+30, y2+30, width=2, fill='black')
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