Avez-vous une question? (216) 97 656 803 hajjriadh@gmail.com
Python

Correction exercices événements tkinter en python

Un cours complet pour maîtriser Correction exercices événements tkinter en python.

0 chapitres 0 QCM Accès gratuit
  1. Objectifs

    • Comprendre et savoir utiliser les événements tkinter de Python.
    • Etre capable de programmer avec Python en utilisant une interface graphique.
  2. Exercice 01

    1. Énoncé
    2. Solution
      ##----- Importation des Modules -----##
      from tkinter import *
      from random import *
      
      ##----- Variables globales -----##
      coul = ['sky blue', 'red', 'blue', 'green', 'purple', 'yellow', 'orange']
      r = 30												# Rayon du cercle
      dim = 500											# Dimensions du canevas carré
      
      ##----- Définition des Fonctions -----##
      def haut(event):
      	global cercle, r
      	v = dessin.coords(cercle)
      	if v[1] > 10:
      		v[1] = v[1] - 10 							# Modification des ordonnées
      		v[3] = v[3] - 10
      		dessin.coords(cercle, v[0], v[1], v[2], v[3])
      
      def bas(event):
      	global cercle, r
      	v = dessin.coords(cercle)
      	if v[3] < dim-10:
      		v[1] = v[1] + 10 							# Modification des ordonnées
      		v[3] = v[3] + 10
      		dessin.coords(cercle, v[0], v[1], v[2], v[3])
      
      def gauche(event):
      	global cercle, r
      	v = dessin.coords(cercle)
      	if v[0] > 10:
      		v[0] = v[0] - 10 							# Modification des abscisses
      		v[2] = v[2] - 10
      		dessin.coords(cercle, v[0], v[1], v[2], v[3])
      
      def droite(event):
      	global cercle, r
      	v = dessin.coords(cercle)
      	if v[2] < dim-10:
      		v[0] = v[0] + 10 							# Modification des abscisses
      		v[2] = v[2] + 10
      		dessin.coords(cercle, v[0], v[1], v[2], v[3])
      
      def change(event):
      	global cercle, coul	# Variables globales
      	v = choice(coul)	# choix d'une couleur au hasard
      	cl = choice(coul)
      
      	dessin.itemconfigure(cercle, outline=v,fill=cl)
      
      ##----- Création de la fenêtre -----##
      fen = Tk()
      fen.title('Un cercle malicieux')
      
      ##----- Création des boutons -----##
      bouton_quitter = Button(fen, text='Quitter', command=fen.destroy)
      bouton_quitter.grid(row=2, column=1, padx=3, pady=3, sticky=S+W+E)
      
      ##----- Création du canevas -----##
      dessin=Canvas(fen, bg="white", width=dim+1, height=dim+1)
      dessin.grid(row = 1, column = 0, columnspan = 2, padx=5, pady=5)
      
      ##----- Objets graphiques -----##
      cercle = dessin.create_oval(dim/2-r, dim/2-r, dim/2+r, dim/2+r, width=5)
      
      ##----- Programme principal -----##
      fen.bind('<Key-Up>', haut)
      fen.bind('<Key-Down>', bas)
      fen.bind('<Key-Left>', gauche)
      fen.bind('<Key-Right>', droite)
      fen.bind('<space>', change)
      fen.mainloop()# Boucle d'attente des événements
      
  3. Exercice 02

    1. Énoncé
    2. Solution
      ##----- Importation des Modules -----##
      from tkinter import *
      ##----- Variables globales -----##
      ancien=None
      ##----- Définition des Fonctions -----##
      def rayon(r):
          global ancien
          r=int(r)
          dessin.delete(ancien)
          ancien=dessin.create_oval(200-r,200-r,200+r, 200+r,fill='sky blue')
      ##----- Création de la fenêtre -----## 
      fen = Tk()
      fen.title('create_scale')
      ##----- Création des boutons -----##
      ##----- Création du canevas -----## 
      dessin = Canvas(fen, bg="ivory", width=400, height=400)
      dessin.pack()
      ##----- Objets graphiques -----## 
      Scale(fen, command=rayon).pack()
      ##----- Programme principal -----##
      fen.mainloop()# Boucle d'attente des événements
      
  4. Exercice 03

    1. Énoncé
    2. Solution
      ##----- Importation des Modules -----##
      from tkinter import *  
      ##----- Variables globales -----##
      ##----- Définition des Fonctions -----##
      def addition(event):
          if entNbr2.get().strip() != '' and entNbr1.get().strip() != '':
              # récupération de la valeur de nbr1 depuis le champ de saisie
              nbr1 = entNbr1.get()
              # récupération de la valeur de nbr2 depuis le champ de saisie
              nbr2 = entNbr2.get()
              if nbr2.isdigit() and nbr1.isdigit():
                  lblResult['text'] = str(int(nbr1) + int(nbr2))
      ##----- Création de la fenêtre -----##
      fen = Tk()
      fen.geometry("315x190")
      fen.title('Addition')
      # Création du label et champ de saisie pour l'entier m
      lblNbr1 = Label(fen , text ="Entrer le premier nombre :  ")
      entNbr1 = Entry(highlightthickness=2)
      entNbr1.config(highlightbackground = "blue",
                     highlightcolor= "green", relief=FLAT)
      lblNbr1.place( x = 10 , y =20)
      
      entNbr1.place( x = 164 , y = 20)
      entNbr1.focus_set()
      # Création du label et champ de saisie pour l'entier n
      lblNbr2 = Label(fen , text ="Entrer le deuxième nombre :  ")
      lblNbr2.place(x = 10 , y = 50 )
      entNbr2 = Entry(fen)
      entNbr2 = Entry(highlightthickness=2)
      entNbr2.config(highlightbackground = "blue",
                     highlightcolor= "green", relief=FLAT)
      entNbr2.place( x = 164 , y = 50)
      
      # Création d'un label qui affiche le résultat
      lblResult = Label(fen , text ="Resultat :  ", font=("Helvetica", 18))
      lblResult.place(x = 164 , y = 110)
      
      ##-- Création des boutons -------##
      ##----- Bouton calculer -----##
      bouton_calculer = Button(fen,bg='green',  text='Calculer')
      bouton_calculer.place(x = 164 , y = 80 , width = 126)
      ##----- Bouton Quitter -----##
      bouton_quitter = Button(fen, text='Quitter',bg='red', command=fen.destroy)
      bouton_quitter.place(x = 164 , y = 150 , width = 126)
      ##----- Les évènements -----##
      fen.bind('<Return>', addition)
      bouton_calculer.bind ("<Button-1>", addition)
      ##----- Programme principal -----##
      fen.mainloop()# Boucle d'attente des événements
      
  5. Exercice 04

    1. Énoncé
    2. Solution
      ##----- Importation des Modules -----##
      from tkinter import *  
      ##----- Variables globales -----##
      ##----- Définition des Fonctions -----##
      def evaluer(event):
          lblResultat.configure(text='resultat = '+str(eval(entOperation.get())))
      def remiseZero(event):
          lblResultat.configure(text='')
          entOperation.delete(0,END)
      ##----- Création de la fenêtre -----##
      fen = Tk()
      fen.geometry("445x160")
      fen.title('Opérations mathématiques')
      # Création du label et champ de saisie pour l'opération
      lblOperation=Label(fen , text ="Saisir une opération mathématique :  ")
      lblOperation.grid(row=2, column=1, padx=3, pady=8, sticky=S+W+E)
      
      entOperation= Entry(fen,bg = 'white', width="20",
                          highlightbackground = "blue", font=("Helvetica", 14),
                          highlightcolor= "green", relief=FLAT)
      entOperation.grid(row=2, column=2, padx=3, pady=8, sticky=S+W+E)
      entOperation.focus_set()
      # Création d'un label qui affiche le résultat
      lblResultat = Label(fen, font=("Helvetica", 20))
      lblResultat.grid(row=4,column=1,columnspan=2, padx=3, pady=10)
      
      #chaine.pack()
      ##----- Bouton Quitter -----##
      bouton_quitter = Button(fen, text='Quitter', width='30'
                              ,bg='red',
                              command=fen.destroy)
      bouton_quitter.grid(row=5,column=2, padx=5, pady=20)
      
      #bouton_quitter.place(x = 164 , y = 150 , width = 126)
      ##----- Les évènements -----##
      entOperation.bind("<Return>",evaluer)
      fen.bind("<Escape>", remiseZero)
      ##----- Programme principal -----##
      fen.mainloop()# Boucle d'attente des événements
      
  6. Exercice 05

    1. Énoncé
    2. Solution
      ##----- Importation des Modules -----##
      from tkinter import *
      ##----- Variables globales -----##
      ##----- Définition des Fonctions -----##
      def addition(event):
          if entNbr1.get().strip() != '':
              # récupération de la valeur de nbr1 depuis le champ de saisie
              nbr1 = entNbr1.get()
              if nbr1.isdigit():
                  entNbr2.delete(0,END)
                  entNbr2.insert(0,str(int(nbr1)*2))
      ##----- Création de la fenêtre -----##
      fen = Tk()
      fen.geometry("315x190")
      fen.title('Doubler un nombre')
      # Création du label et champ de saisie pour l'entier m
      lblNbr1 = Label(fen , text ="Saisir un nombre entier :  ")
      entNbr1 = Entry(highlightthickness=2)
      entNbr1.config(highlightbackground = "blue",
                     highlightcolor= "green", relief=FLAT)
      lblNbr1.place( x = 10 , y =20)
      
      entNbr1.place( x = 164 , y = 20)
      entNbr1.focus_set()
      # Création du label et champ de saisie pour l'entier n
      lblNbr2 = Label(fen , text ="Le double de N est : ")
      lblNbr2.place(x = 10 , y = 50 )
      entNbr2 = Entry(fen)
      entNbr2 = Entry(highlightthickness=2)
      entNbr2.config(highlightbackground = "blue",
                     highlightcolor= "green", relief=FLAT)
      entNbr2.place( x = 164 , y = 50)
      ##-- Création des boutons -------##
      ##----- Bouton calculer -----##
      bouton_calculer = Button(fen,bg='green',  text='Calculer')
      bouton_calculer.place(x = 164 , y = 80 , width = 126)
      ##----- Bouton Quitter -----##
      bouton_quitter = Button(fen, text='Quitter',bg='red', command=fen.destroy)
      bouton_quitter.place(x = 164 , y = 150 , width = 126)
      ##----- Les évènements -----##
      fen.bind('<Return>', addition)
      bouton_calculer.bind ("<Button-1>", addition)
      ##----- Programme principal -----##
      fen.mainloop()# Boucle d'attente des événements