Correction exercice Tkinter avec classe

Correction exercice Tkinter avec classe

  1. Objectifs

    • Etre capable de programmer des applications tkinter avec des classes
  2. Exercice 01

    1. Énoncé
    2. Correction
      • ##-----Importation des Modules-----##
        import tkinter as tk
        class Application(tk.Tk):
            def __init__(self):
                tk.Tk.__init__(self)
                self.creer_widgets()
            def creer_widgets(self):
                self.grid()
                ##-----Création de label de texte-----##
                self.label = tk.Label(self, text='Ici du texte.')
                self.label.grid(row = 0, column = 0, columnspan=2, padx=3, pady=3)
                ##-----Création des boutons-----##
                self.bouton = tk.Button(self, text='Quitter', width=19, command=self.destroy)
                self.bouton.grid(row = 2, column = 1, padx=3, pady=3)
        
                self.bouton = tk.Button(self, text='Recommencer', width=20)
                self.bouton.grid(row = 2, column = 0, padx=3, pady=3)
                ##-----Création du canevas-----##
                self.Canvas = tk.Canvas(self, bg="ivory", width=301, height=301)
                self.Canvas.grid(row = 1, column = 0, columnspan = 2, padx=5, pady=5)
                ##-----La grille-----##
                lignes = []
                for i in range(4):
                    lignes.append(self.Canvas.create_line(0, 100*i+2, 303, 100*i+2, width=3, fill='green'))
                    lignes.append(self.Canvas.create_line(100*i+2, 0, 100*i+2, 303, width=3, fill='green'))
                    
        
        if __name__ == "__main__":
            app = Application()
            app.title("Morpion")
            ##----- Programme principal -----##
            app.mainloop()# Boucle d'attente des événements
        



  3. Exercice 02

    1. Énoncé
    2. Solution
      • import tkinter as tk
        import random as rd
        
        class AppliCanevas(tk.Tk):
            def __init__(self):
                tk.Tk.__init__(self)
                self.size = 300
                self.creer_widgets()
        
            def creer_widgets(self):
                # création canevas
                self.canv = tk.Canvas(self, bg="ivory", height=self.size,
                                      width=self.size)
                self.canv.pack(side=tk.LEFT)
                # boutons
                self.bouton_cercles = tk.Button(self, text="Tracer 20 cercle !",width=15,
                                        bg="sky blue",command=self.dessinerCercles)
                self.bouton_cercles.pack(side=tk.TOP)
                self.bouton_lignes = tk.Button(self, text="Tracer 20  lignes !",width=15,
                                        bg="light blue",command=self.dessinerLignes)
                self.bouton_lignes.pack()
                self.bouton_triangles = tk.Button(self, text="Tracer 4 triangles !",width=15,
                                        bg="light blue",command=self.dessinerTriangles)
                self.bouton_triangles.pack()
                self.bouton_quitter = tk.Button(self, text="Quitter",width=15,bg="cyan",
                                                command=self.destroy)
                self.bouton_quitter.pack(side=tk.BOTTOM)
        
            def rd_col(self):
                return rd.choice(("black", "red", "green", "blue", "yellow", "magenta",
                                  "cyan", "white", "purple"))
        
            def dessinerCercles(self):
                for i in range(20):
                    x, y = [rd.randint(1, self.size) for j in range(2)]
                    diameter = rd.randint(1, 50)
                    self.canv.create_oval(x, y, x+diameter, y+diameter,
                                          fill=self.rd_col())
        
            def dessinerLignes(self):
                for i in range(20):
                    x, y, x2, y2 = [rd.randint(1, self.size) for j in range(4)]
                    self.canv.create_line(x, y, x2, y2, fill=self.rd_col())
            def dessinerTriangles(self):
                for i in range(4):
                    x, y, x2, y2 = [rd.randint(1, 200) for j in range(4)]
                    self.canv.create_rectangle(x, y, x2, y2, fill=self.rd_col())
        
        
        if __name__ == "__main__":
            app = AppliCanevas()
            app.title("Mes formes géomètriques !")
            app.mainloop()
        
  4. Exercice 03

    1. Énoncé
    2. Solution
      • import tkinter as tk
        from tkinter import ttk
        import tkinter.scrolledtext as st
        from tkinter import messagebox
        from datetime import date, timedelta
        numjour=4
        class App(tk.Tk):
            def __init__(self):
                super(App, self).__init__()
         
                self.title("Tkinter Label Frame")
                self.minsize(500,300)
                # Créer un labelFrame       
                self.labelFrame = ttk.LabelFrame(self, text = "Afficher les jours de l'année")
                self.labelFrame.grid(column = 0, row = 0, padx = 20, pady = 10)
                self.ComboboxJours()
                self.EntAnnee()
                self.btn()
                self.ScrolledText()
            def callback(self,even=None):
                global numjour
                numjour=int(self.choix.current())
                if self.choix.get() == "Lundi" : numjour=0
                messagebox.showinfo("Title", str(numjour))
            # Créer combobox des jours de la semaine
            def ComboboxJours(self):
                ttk.Label(self.labelFrame, text = "Choisir un jour").grid(column=2, row=1, sticky = tk.W)
        
                lesJours = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche']
                self.choix = ttk.Combobox(self.labelFrame,
                                            values=lesJours)
                self.choix.grid(column=3, row=1)
                self.choix.bind("<<ComboboxSelected>>", self.callback)
        
             # Créer zone de saisie
            def EntAnnee(self):
                self.entryVariable = tk.StringVar()
         
                ttk.Label(self.labelFrame, text = "Saisir une année").grid(column=0, row=1, sticky = tk.W)
                self.Entry = ttk.Entry(self.labelFrame,textvariable=self.entryVariable).grid(column=1, row=1, sticky = tk.W)
            # Créer les boutons
            def btn(self):
                 ttk.Button(self.labelFrame, text="Quitter",width=20,
                            command=self.destroy).grid(column=3, row=10,pady=50, sticky = tk.W)
        
                 ttk.Button(self.labelFrame, text="Afficher",width=20,
                            command=self.TousJours).grid(columnspan=4, row=3,pady=20)        
            def joursem(self,D):
                return ('Lundi', 'Mardi', 'Mercredi', 'Jeudi',
                    'Vendredi', 'Samedi', 'Dimanche')[int(D)-1]
            def Mois(self,D):
                return ('Janvier','Fevrier','Mars','Avril','Mai',
                        'Juin','Juillet','Août','Septembre','Octobre',
                        'Novembre','Decembre')[int(D)-1]
            def TousJours(self):
                # 1er janvier de l'année donnée
                year=self.entryVariable.get()
                AnneeEnCour = date.today().year
                dt = date(int(year), 1, 1)
                # Premier vendredi de l'année donnée
                messagebox.showinfo("Title", numjour)
                dt += timedelta(days = numjour - dt.weekday())
                list1=[]
                #ttk.Entry(self.labelFrame, width=100).grid(columnspan=4, row=4,pady=20)
                # disabling the state
                text_area = st.ScrolledText(self.labelFrame, 
                                    width = 40,  
                                    height = 8,  
                                    font = ("Times New Roman", 
                                            15))
                text_area.grid(columnspan = 4,row=5, pady = 10, padx = 10)
                # Inserting Text which is read only
                i=1
                while int(dt.year) == int(year):
                    #yield int(dt)
                    text_area.insert(tk.INSERT,str(i)+ " - " + self.joursem(dt.strftime("%w"))
                                     + ' le  ' + dt.strftime("%d") + " "
                                     + self.Mois(dt.strftime("%m"))
                                     + "  " + dt.strftime("%Y")+"\n")
                    dt += timedelta(days = 7)
                    i=i+1
                # Making the text read only 
                text_area.configure(state ='disabled')
            # Créer la liste d'affichage
            def ScrolledText(self):
                text_area = st.ScrolledText(self.labelFrame, 
                                    width = 40,  
                                    height = 8,  
                                    font = ("Times New Roman", 
                                            15))
                text_area.grid(columnspan = 4,row=5, pady = 10, padx = 10)
                # Inserting Text which is read only 
                text_area.configure(state ='disabled')
               
              
        if __name__ == "__main__":
            app = App()
            app.title("Affichage des jours !")
            app.mainloop()
        



Laisser un commentaire

Abonnez vous à notre chaîne YouTube gratuitement