Planification → Composants → Interactions → Test → Amélioration
Menu interactif : Interface permettant à l'utilisateur de choisir parmi plusieurs options disponibles.
- Définir les options du menu
- Afficher le menu de manière claire
- Demander la sélection de l'utilisateur
- Valider la sélection
- Exécuter l'action correspondante
- Titre du menu
- Options numérotées
- Instructions claires
- Validation de la sélection
- Boucle de retour au menu
def afficher_menu():
print("=== MENU PRINCIPAL ===")
print("1. Option 1")
print("2. Option 2")
print("3. Option 3")
print("4. Quitter")
print("=====================")
while True:
afficher_menu()
choix = input("Votre choix : ")
if choix == "1":
# Exécuter action 1
pass
elif choix == "2":
# Exécuter action 2
pass
elif choix == "3":
# Exécuter action 3
pass
elif choix == "4":
print("Au revoir !")
break
else:
print("Option invalide !")
def saisir_choix():
while True:
try:
choix = input("Votre choix (1-4) : ")
if choix in ["1", "2", "3", "4"]:
return choix
else:
print("Veuillez choisir entre 1 et 4")
except KeyboardInterrupt:
print("\nInterruption par l'utilisateur")
return "4"
def afficher_menu():
print("\n=== MENU PRINCIPAL ===")
print("1. Afficher un message")
print("2. Saisir des données")
print("3. Calculer un résultat")
print("4. Quitter")
print("=====================")
def option_1():
print("Vous avez choisi l'option 1 !")
def option_2():
nom = input("Entrez votre nom : ")
print(f"Bonjour {nom} !")
def option_3():
a = int(input("Entrez un nombre : "))
b = int(input("Entrez un autre nombre : "))
print(f"La somme est : {a + b}")
def main():
while True:
afficher_menu()
choix = input("Votre choix (1-4) : ")
if choix == "1":
option_1()
elif choix == "2":
option_2()
elif choix == "3":
option_3()
elif choix == "4":
print("Au revoir !")
break
else:
print("Option invalide ! Veuillez choisir entre 1 et 4.")
# Exécution du programme
if __name__ == "__main__":
main()
• Menu clair : Afficher les options de manière ordonnée et lisible
• Validation : Vérifier que la sélection est valide
• Boucle infinie : Utiliser une boucle avec condition de sortie
Saisie utilisateur : Processus permettant à l'utilisateur d'entrer des données dans le programme.
- Instructions claires
- Validation des données
- Messages d'erreur pertinents
- Redemande en cas d'erreur
- Type de données attendu
nom = input("Entrez votre nom : ")
print(f"Bonjour {nom} !")
while True:
nom = input("Entrez votre nom (minimum 2 caractères) : ")
if len(nom) >= 2:
break
else:
print("Le nom doit contenir au moins 2 caractères")
def saisir_age():
while True:
try:
age = int(input("Entrez votre âge : "))
if 0 <= age <= 120:
return age
else:
print("L'âge doit être entre 0 et 120")
except ValueError:
print("Veuillez entrer un nombre entier")
def saisir_informations():
# Saisie du nom
while True:
nom = input("Entrez votre nom : ").strip()
if len(nom) >= 2 and nom.isalpha():
break
print("Le nom doit contenir au moins 2 lettres")
# Saisie de l'âge
while True:
try:
age = int(input("Entrez votre âge (0-120) : "))
if 0 <= age <= 120:
break
else:
print("L'âge doit être entre 0 et 120")
except ValueError:
print("Veuillez entrer un nombre entier")
# Saisie de l'email
while True:
email = input("Entrez votre email : ").strip()
if "@" in email and "." in email:
break
print("Email invalide, exemple : utilisateur@domaine.com")
return nom, age, email
# Exemple d'utilisation
nom, age, email = saisir_informations()
print(f"\nInformations saisies :")
print(f"Nom : {nom}")
print(f"Âge : {age}")
print(f"Email : {email}")
• Validation immédiate : Vérifier la saisie dès l'entrée
• Messages clairs : Expliquer les attentes de l'utilisateur
• Boucle de correction : Redemander la saisie en cas d'erreur
Affichage structuré : Présentation organisée des données pour une meilleure lisibilité.
- Alignement des colonnes
- En-têtes clairs
- Séparation visuelle
- Formatage cohérent
- Hiérarchie d'information
donnees = [
["Alice", 25, "Paris"],
["Bob", 30, "Lyon"],
["Charlie", 22, "Marseille"]
]
print(f"{'Nom':<12} {'Âge':<5} {'Ville':<15}")
print("-" * 35)
for personne in donnees:
print(f"{personne[0]:<12} {personne[1]:<5} {personne[2]:<15}")
def afficher_tableau(en_tetes, donnees):
# Calcul des largeurs maximales
largeurs = []
for i in range(len(en_tetes)):
max_larg = max(len(str(en_tetes[i])), max(len(str(row[i])) for row in donnees))
largeurs.append(max_larg)
# Affichage des en-têtes
ligne = ""
for i, en_tete in enumerate(en_tetes):
ligne += f"{en_tete:<{largeurs[i]+2}}"
print(ligne)
print("-" * len(ligne))
# Affichage des données
for ligne_donnees in donnees:
ligne = ""
for i, donnee in enumerate(ligne_donnees):
ligne += f"{donnee:<{largeurs[i]+2}}"
print(ligne)
def afficher_liste_structuree():
# Données à afficher
en_tetes = ["Nom", "Âge", "Ville", "Profession"]
donnees = [
["Alice Martin", 25, "Paris", "Développeuse"],
["Bob Dupont", 30, "Lyon", "Designer"],
["Charlie Moreau", 22, "Marseille", "Étudiant"],
["Diana Leroy", 28, "Bordeaux", "Marketing"]
]
# Affichage du tableau
print("=" * 50)
print("LISTE DES PERSONNES")
print("=" * 50)
# En-têtes
print(f"{'Nom':<15} {'Âge':<5} {'Ville':<12} {'Profession':<15}")
print("-" * 50)
# Données
for personne in donnees:
print(f"{personne[0]:<15} {personne[1]:<5} {personne[2]:<12} {personne[3]:<15}")
print("=" * 50)
# Exemple d'utilisation
afficher_liste_structuree()
• Alignement cohérent : Utiliser des largeurs fixes pour l'alignement
• Séparation visuelle : Lignes de séparation pour clarifier
• Hiérarchie d'information : Organiser les données de manière logique
Tkinter : Bibliothèque graphique intégrée à Python pour créer des interfaces graphiques.
- fenêtre principale (Tk)
- widgets (Label, Entry, Button)
- événements (click, saisie)
- gestionnaires de disposition (pack, grid)
- fonctions de callback
import tkinter as tk
# Création de la fenêtre principale
fenetre = tk.Tk()
fenetre.title("Mon application")
fenetre.geometry("400x300")
# Label
label = tk.Label(fenetre, text="Bonjour !", font=("Arial", 14))
# Bouton
bouton = tk.Button(fenetre, text="Cliquez-moi")
# Champ de saisie
entree = tk.Entry(fenetre)
# Positionnement avec pack
label.pack(pady=10)
entree.pack(pady=5)
bouton.pack(pady=10)
# Démarrage de l'interface
fenetre.mainloop()
import tkinter as tk
from tkinter import messagebox
class Application:
def __init__(self):
self.fenetre = tk.Tk()
self.fenetre.title("Interface de base")
self.fenetre.geometry("400x300")
# Création des widgets
self.label_titre = tk.Label(self.fenetre, text="Bienvenue !", font=("Arial", 16))
self.label_titre.pack(pady=20)
self.label_saisie = tk.Label(self.fenetre, text="Entrez votre nom :")
self.label_saisie.pack()
self.entree_nom = tk.Entry(self.fenetre, width=30)
self.entree_nom.pack(pady=5)
self.bouton_saluer = tk.Button(self.fenetre, text="Saluer", command=self.saluer)
self.bouton_saluer.pack(pady=10)
self.bouton_quitter = tk.Button(self.fenetre, text="Quitter", command=self.fenetre.quit)
self.bouton_quitter.pack(pady=5)
# Zone de texte pour afficher les messages
self.zone_texte = tk.Text(self.fenetre, height=5, width=40)
self.zone_texte.pack(pady=10)
def saluer(self):
nom = self.entree_nom.get()
if nom:
message = f"Bonjour {nom} !"
self.zone_texte.insert(tk.END, message + "\n")
self.entree_nom.delete(0, tk.END)
else:
messagebox.showwarning("Avertissement", "Veuillez entrer un nom")
def run(self):
self.fenetre.mainloop()
# Exécution de l'application
app = Application()
app.run()
• Widget principal : Créer une instance de Tk() pour la fenêtre
• Disposition : Utiliser pack() ou grid() pour positionner les widgets
• Événements : Associer des fonctions aux actions des boutons
Interactions multiples : Interface permettant à l'utilisateur d'effectuer plusieurs types d'actions différentes.
- Clic sur boutons
- Saisie dans champs
- Sélection dans listes
- Navigation entre écrans
- Réactions aux événements
import tkinter as tk
from tkinter import ttk
class InterfaceComplexe:
def __init__(self):
self.fenetre = tk.Tk()
self.fenetre.title("Interface avec interactions multiples")
self.fenetre.geometry("500x400")
# Variables
self.nom = tk.StringVar()
self.age = tk.IntVar(value=18)
self.ville = tk.StringVar()
# Cadre principal
cadre_principal = ttk.Frame(self.fenetre, padding=10)
cadre_principal.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
# Labels et champs
ttk.Label(cadre_principal, text="Nom :").grid(row=0, column=0, sticky=tk.W)
ttk.Entry(cadre_principal, textvariable=self.nom).grid(row=0, column=1, padx=5)
ttk.Label(cadre_principal, text="Âge :").grid(row=1, column=0, sticky=tk.W)
ttk.Spinbox(cadre_principal, from_=0, to=120, textvariable=self.age).grid(row=1, column=1, padx=5)
ttk.Label(cadre_principal, text="Ville :").grid(row=2, column=0, sticky=tk.W)
villes = ["Paris", "Lyon", "Marseille", "Bordeaux"]
ttk.Combobox(cadre_principal, textvariable=self.ville, values=villes).grid(row=2, column=1, padx=5)
# Boutons
ttk.Button(cadre_principal, text="Afficher", command=self.afficher_infos).grid(row=3, column=0, pady=10)
ttk.Button(cadre_principal, text="Effacer", command=self.effacer_champs).grid(row=3, column=1, pady=10)
# Zone d'affichage
self.zone_affichage = tk.Text(cadre_principal, height=8, width=50)
self.zone_affichage.grid(row=4, column=0, columnspan=2, pady=10)
def afficher_infos(self):
infos = f"Nom: {self.nom.get()}\n"
infos += f"Âge: {self.age.get()}\n"
infos += f"Ville: {self.ville.get()}\n"
self.zone_affichage.delete(1.0, tk.END)
self.zone_affichage.insert(tk.END, infos)
def effacer_champs(self):
self.nom.set("")
self.age.set(18)
self.ville.set("")
import tkinter as tk
from tkinter import ttk, messagebox
class ApplicationInteractions:
def __init__(self):
self.fenetre = tk.Tk()
self.fenetre.title("Application avec interactions multiples")
self.fenetre.geometry("600x500")
# Variables
self.nom = tk.StringVar()
self.email = tk.StringVar()
self.age = tk.IntVar(value=18)
self.sexe = tk.StringVar(value="Homme")
self.hobbies = []
# Création de l'interface
self.creer_interface()
def creer_interface(self):
# Cadre principal
cadre_principal = ttk.Frame(self.fenetre, padding=20)
cadre_principal.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
# Titre
titre = ttk.Label(cadre_principal, text="Formulaire d'inscription", font=("Arial", 16, "bold"))
titre.grid(row=0, column=0, columnspan=2, pady=10)
# Nom
ttk.Label(cadre_principal, text="Nom :").grid(row=1, column=0, sticky=tk.W, pady=5)
ttk.Entry(cadre_principal, textvariable=self.nom, width=30).grid(row=1, column=1, padx=10, pady=5)
# Email
ttk.Label(cadre_principal, text="Email :").grid(row=2, column=0, sticky=tk.W, pady=5)
ttk.Entry(cadre_principal, textvariable=self.email, width=30).grid(row=2, column=1, padx=10, pady=5)
# Âge
ttk.Label(cadre_principal, text="Âge :").grid(row=3, column=0, sticky=tk.W, pady=5)
ttk.Spinbox(cadre_principal, from_=0, to=120, textvariable=self.age, width=27).grid(row=3, column=1, padx=10, pady=5)
# Sexe
ttk.Label(cadre_principal, text="Sexe :").grid(row=4, column=0, sticky=tk.W, pady=5)
cadre_sexe = ttk.Frame(cadre_principal)
cadre_sexe.grid(row=4, column=1, sticky=tk.W, padx=10, pady=5)
ttk.Radiobutton(cadre_sexe, text="Homme", variable=self.sexe, value="Homme").pack(side=tk.LEFT)
ttk.Radiobutton(cadre_sexe, text="Femme", variable=self.sexe, value="Femme").pack(side=tk.LEFT)
ttk.Radiobutton(cadre_sexe, text="Autre", variable=self.sexe, value="Autre").pack(side=tk.LEFT)
# Hobbies (Checkbuttons)
ttk.Label(cadre_principal, text="Hobbies :").grid(row=5, column=0, sticky=tk.W, pady=5)
cadre_hobbies = ttk.Frame(cadre_principal)
cadre_hobbies.grid(row=5, column=1, sticky=tk.W, padx=10, pady=5)
self.hobby1 = tk.BooleanVar()
self.hobby2 = tk.BooleanVar()
self.hobby3 = tk.BooleanVar()
self.hobby4 = tk.BooleanVar()
ttk.Checkbutton(cadre_hobbies, text="Sport", variable=self.hobby1).pack(anchor=tk.W)
ttk.Checkbutton(cadre_hobbies, text="Musique", variable=self.hobby2).pack(anchor=tk.W)
ttk.Checkbutton(cadre_hobbies, text="Lecture", variable=self.hobby3).pack(anchor=tk.W)
ttk.Checkbutton(cadre_hobbies, text="Jeux vidéo", variable=self.hobby4).pack(anchor=tk.W)
# Boutons d'action
cadre_boutons = ttk.Frame(cadre_principal)
cadre_boutons.grid(row=6, column=0, columnspan=2, pady=20)
ttk.Button(cadre_boutons, text="Soumettre", command=self.soumettre).pack(side=tk.LEFT, padx=5)
ttk.Button(cadre_boutons, text="Effacer", command=self.effacer).pack(side=tk.LEFT, padx=5)
ttk.Button(cadre_boutons, text="Quitter", command=self.fenetre.quit).pack(side=tk.LEFT, padx=5)
# Zone d'affichage
ttk.Label(cadre_principal, text="Résultat :").grid(row=7, column=0, sticky=tk.W, pady=(10,0))
self.zone_resultat = tk.Text(cadre_principal, height=8, width=60)
self.zone_resultat.grid(row=8, column=0, columnspan=2, pady=5)
def soumettre(self):
# Collecte des hobbies
hobbies_selectionnes = []
if self.hobby1.get(): hobbies_selectionnes.append("Sport")
if self.hobby2.get(): hobbies_selectionnes.append("Musique")
if self.hobby3.get(): hobbies_selectionnes.append("Lecture")
if self.hobby4.get(): hobbies_selectionnes.append("Jeux vidéo")
# Affichage des résultats
resultat = f"Nom: {self.nom.get()}\n"
resultat += f"Email: {self.email.get()}\n"
resultat += f"Âge: {self.age.get()}\n"
resultat += f"Sexe: {self.sexe.get()}\n"
resultat += f"Hobbies: {', '.join(hobbies_selectionnes) if hobbies_selectionnes else 'Aucun'}\n"
self.zone_resultat.delete(1.0, tk.END)
self.zone_resultat.insert(tk.END, resultat)
def effacer(self):
self.nom.set("")
self.email.set("")
self.age.set(18)
self.sexe.set("Homme")
self.hobby1.set(False)
self.hobby2.set(False)
self.hobby3.set(False)
self.hobby4.set(False)
self.zone_resultat.delete(1.0, tk.END)
def run(self):
self.fenetre.mainloop()
# Exécution de l'application
app = ApplicationInteractions()
app.run()
• Variables tkinter : Utiliser StringVar, IntVar pour lier les widgets
• Widgets multiples : Combiner Entry, Button, Checkbutton, Radiobutton
• Événements liés : Connecter les actions aux fonctions appropriées
- Planification : Définir les besoins et les composants
- Création : Implémenter les widgets de base
- Interaction : Connecter les événements aux actions
- Validation : Vérifier les saisies utilisateur
- Test : Évaluer l'expérience utilisateur
- Un menu interactif facilite la navigation de l'utilisateur
- La validation des saisies améliore la robustesse du programme
- L'affichage structuré rend les données plus lisibles
- Les interfaces graphiques utilisent des widgets tkinter
- Les interactions multiples enrichissent l'expérience utilisateur
Planification → Composants → Interactions → Validation → Affichage → Feedback