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
| from tkinter import *
from math import *
# définition des gestionnaires
# d'événements :
def depl():
"deplacement lineaire de la balle suivant un angle defini"
global x,y,r,at,angle
xt,yt=x,y
if (x>235 or x<15 or y>235 or y<15):
if x>235:
xt=235
if x<15:
xt=15
if y>235:
yt=235
if y<15:
yt=15
at=pi/2+at
x=xt+d*cos(at)
y=yt+d*sin(at)
can1.coords(oval1,x-r,y-r,x+r,y+r)
can1.create_line(xt,yt,x,y,width=2,fill='blue')
print(x,y,at)
if flag >0:
fen1.after(250,depl) # => boucler, après 50 millisecondes
def stop_it():
"arrêt de l'animation"
global flag
flag =0
def start_it():
"démarrage de l'animation"
global flag
if flag ==0: # pour ne lancer quune seule boucle
flag =1
depl()
#========== Programme principal =============
# les variables suivantes seront utilisées de manière globale :
x, y = 100, 100 # coordonnées initiales
r=15
d=30
flag =0 # commutateur
at=pi/3
# 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(x, y, x+30, y+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