Outils pour utilisateurs

Outils du site


issue51:python_partie_25_pp._7-14

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentesRévision précédente
Prochaine révision
Révision précédente
issue51:python_partie_25_pp._7-14 [2011/08/28 15:37] andre_domenechissue51:python_partie_25_pp._7-14 [2011/08/31 21:35] (Version actuelle) fredphil91
Ligne 289: Ligne 289:
 **The “funcNumButton routine receives the value we passed from the button press. The only thing that is different from the example above is what if the user pressed the decimal button (“.”). Below, you'll see that we use a boolean variable to hold the fact they pressed the decimal button, and, on the next click, we deal with it. That's what the “if self.DecimalNext == True:” line is all about. Let's walk through it. **The “funcNumButton routine receives the value we passed from the button press. The only thing that is different from the example above is what if the user pressed the decimal button (“.”). Below, you'll see that we use a boolean variable to hold the fact they pressed the decimal button, and, on the next click, we deal with it. That's what the “if self.DecimalNext == True:” line is all about. Let's walk through it.
  
-The user clicks 3, then 2, then the decimal, then 4, to create “32.4”. We handle the 3 and 2 clicks through the “funcNumButton” routine. We check to see if self.DecimalNext is True (which in this case it isn't until the user clicks the “.” button). If not, we simply multiply the held value (self.CurrentValue) by 10 and add the incoming value. When the user clicks the “.”, the callback “funcFuncButton” is called with the “Dec” value. All we do is set the boolean variable “self.DecimalNext” to True. When the user clicks the 4, we will test the “self.DecimalNext” value and, since it's true, we play some magic. First, we increment the self.DecimalCount variable. This tells us how many decimal places we are working with. We then take the incoming value, multiply it by (10<nowiki>**</nowiki>-self.DecimalCount). Using this magic operator, we get a simple “raised to the power of” function. For example 10<nowiki>**</nowiki>2 returns 100. 10<nowiki>**</nowiki>-2 returns 0.01. Eventually, using this routine will result in a rounding issue, but for our simple calculator, it will work for most reasonable decimal numbers. I'll leave it to you to work out a better function. Think of this as your homework for this month.**+The user clicks 3, then 2, then the decimal, then 4, to create “32.4”. We handle the 3 and 2 clicks through the “funcNumButton” routine. We check to see if self.DecimalNext is True (which in this case it isn't until the user clicks the “.” button). If not, we simply multiply the held value (self.CurrentValue) by 10 and add the incoming value. When the user clicks the “.”, the callback “funcFuncButton” is called with the “Dec” value. All we do is set the boolean variable “self.DecimalNext” to True. When the user clicks the 4, we will test the “self.DecimalNext” value and, since it's true, we play some magic. First, we increment the self.DecimalCount variable. This tells us how many decimal places we are working with. We then take the incoming value, multiply it by (10<nowiki>*</nowiki><nowiki>*</nowiki>-self.DecimalCount). Using this magic operator, we get a simple “raised to the power of” function. For example 10<nowiki>*</nowiki><nowiki>*</nowiki>2 returns 100. 10<nowiki>*</nowiki><nowiki>*</nowiki>-2 returns 0.01. Eventually, using this routine will result in a rounding issue, but for our simple calculator, it will work for most reasonable decimal numbers. I'll leave it to you to work out a better function. Think of this as your homework for this month.**
  
 La routine « foncBoutonNumerique » reçoit la valeur que nous lui passons en appuyant sur un bouton. La seule chose qui diffère de l'exemple ci-dessus est lorsque l'utilisateur appuie sur ​​le bouton de décimale (« . »). Ci-dessous, vous verrez que nous utilisons une variable booléenne pour retenir le fait qu'il a déjà appuyé sur le bouton décimal, et, au prochain clic, on s'en occupe. D'où la ligne « if self.PartieDecimale == True: ». Nous allons procéder pas à pas. La routine « foncBoutonNumerique » reçoit la valeur que nous lui passons en appuyant sur un bouton. La seule chose qui diffère de l'exemple ci-dessus est lorsque l'utilisateur appuie sur ​​le bouton de décimale (« . »). Ci-dessous, vous verrez que nous utilisons une variable booléenne pour retenir le fait qu'il a déjà appuyé sur le bouton décimal, et, au prochain clic, on s'en occupe. D'où la ligne « if self.PartieDecimale == True: ». Nous allons procéder pas à pas.
  
-L'utilisateur clique sur 3, puis 2, puis le point décimal, puis 4 pour créer « 32.4 ». Nous traitons les clics sur 3 et 2 grâce à la routine « foncBoutonNumerique ». Nous vérifions pour voir si self.PartieDecimale est vrai (ce qu'il n'est pas tant que l'utilisateur n'a pas cliqué sur le bouton « . »). Sinon, nous multiplions simplement la valeur de self.ValeurCourante par 10 et ajoutons la nouvelle valeur. Lorsque l'utilisateur clique sur le « . », la fonction de rappel « foncBoutonFonction » est appelée avec la valeur « Dec ». Tout ce que nous faisons est de régler la variable booléenne « self.PartieDecimale » à vrai (True). Lorsque l'utilisateur clique sur le 4, nous allons tester la valeur de « self.PartieDecimale » et, puisqu'elle est vraie, nous faisons un peu de magie. Premièrement, on incrémente la variable self.CompteDecimales, qui nous indique le nombre de décimales avec lequel nous travaillons. Nous prenons ensuite la nouvelle valeur entrante, la multiplions par (10<nowiki>**</ nowiki>-self.CompteDecimales). En utilisant cet opérateur magique, nous obtenons une simple fonction « élévation à la puissance ». Par exemple 10<nowiki>**</nowiki>2 renvoie 100. 10<nowiki>**</ nowiki>-2 retourne 0.01. Parfois, en utilisant cette routine, cela conduit à un problème d'arrondi, mais pour notre calculatrice simple, cela fonctionnera pour la plupart des nombres décimaux raisonnables. Je vais vous laisser le soin de travailler à une meilleure fonction. Prenez cela comme vos devoirs pour ce mois-ci.+L'utilisateur clique sur 3, puis 2, puis le point décimal, puis 4 pour créer « 32.4 ». Nous traitons les clics sur 3 et 2 grâce à la routine « foncBoutonNumerique ». Nous vérifions pour voir si self.PartieDecimale est vrai (ce qu'il n'est pas tant que l'utilisateur n'a pas cliqué sur le bouton « . »). Sinon, nous multiplions simplement la valeur de self.ValeurCourante par 10 et ajoutons la nouvelle valeur. Lorsque l'utilisateur clique sur le « . », la fonction de rappel « foncBoutonFonction » est appelée avec la valeur « Dec ». Tout ce que nous faisons est de régler la variable booléenne « self.PartieDecimale » à vrai (True). Lorsque l'utilisateur clique sur le 4, nous allons tester la valeur de « self.PartieDecimale » et, puisqu'elle est vraie, nous faisons un peu de magie. Premièrement, on incrémente la variable self.CompteDecimales, qui nous indique le nombre de décimales avec lequel nous travaillons. Nous prenons ensuite la nouvelle valeur entrante, la multiplions par (10<nowiki>*</nowiki><nowiki>*</nowiki>-self.CompteDecimales). En utilisant cet opérateur magique, nous obtenons une simple fonction « élévation à la puissance ». Par exemple 10<nowiki>*</nowiki><nowiki>*</nowiki>2 renvoie 100. 10<nowiki>*</nowiki><nowiki>*</nowiki>-2 retourne 0.01. Parfois, en utilisant cette routine, cela conduit à un problème d'arrondi, mais pour notre calculatrice simple, cela fonctionnera pour la plupart des nombres décimaux raisonnables. Je vais vous laisser le soin de travailler à une meilleure fonction. Prenez cela comme vos devoirs pour ce mois-ci.
  
 **The “funcClear” routine simply clears the two holding variables, then sets the display. **The “funcClear” routine simply clears the two holding variables, then sets the display.
Ligne 356: Ligne 356:
  
 Le mois prochain, nous allons continuer à explorer Tkinter et la richesse de ses widgets. Dans un prochain article, nous verrons un concepteur d'interface graphique pour Tkinter appelé PAGE. En attendant, amusez-vous bien. Je pense que vous apprécierez Tkinter. Le mois prochain, nous allons continuer à explorer Tkinter et la richesse de ses widgets. Dans un prochain article, nous verrons un concepteur d'interface graphique pour Tkinter appelé PAGE. En attendant, amusez-vous bien. Je pense que vous apprécierez Tkinter.
 +
 +====== CODE PAGE 7 ======
 +remplacer l'anglais par COLONNES et LIGNES
 +
 +====== CODE PAGE 8 ======
 +  class App:
 +    def __init__(self, principale):
 +        cadre = Frame(principale)
 +        self.lblTexte = Label(cadre, text = "Voici un widget label")
 +        self.btnQuitter = Button(cadre, text="Quitter", fg="red", command=cadre.quit)
 +        self.btnBonjour = Button(cadre, text="Bonjour", command=self.DitUnTruc)
 +        cadre.grid(column = 0, row = 0)
 +        self.lblTexte.grid(column = 0, row = 0, columnspan = 2)
 +        self.btnBonjour.grid(column = 0, row = 1)
 +        self.btnQuitter.grid(column = 1, row = 1)
 +
 +
 +====== CODE PAGE 9 ======
 +en haut à droite : remplacer CLEAR par EFFACER
 +
 +juste en dessous :
 +
 +  from Tkinter import *
 +  def Demarrage():
 +    global val, calc, racine
 +    racine = Tk()
 +    racine.title('Calculatrice simple')
 +    racine.geometry('247x330+469+199')
 +    calc = Calculatrice(racine)
 +    racine.mainloop()
 +
 +en bas à gauche :
 +
 +  class Calculatrice():
 +    def __init__(self,racine):
 +        principale = Frame(racine)
 +        self.ValeurCourante = 0 
 +        self.ValeurAncienne = 0
 +        self.FonctionCourante = ''
 +        self.AffichageCourant = StringVar()
 +        self.AffichageCourant.set('0')
 +        self.PartieDecimale = False
 +        self.CompteDecimales = 0
 +        self.DefinirWidgets(principale)
 +        self.PlacerWidgets(principale)
 +
 +====== CODE PAGE 10 ======
 +        self.btn1 = Button(principale, text = '1',width = 4,height=3)
 +        self.btn1.bind('<ButtonRelease-1>', lambda e: self.foncBoutonNumerique(1))
 +        self.btn2 = Button(principale, text = '2',width = 4,height=3)
 +        self.btn2.bind('<ButtonRelease-1>', lambda e: self.foncBoutonNumerique(2))
 +        self.btn3 = Button(principale, text = '3',width = 4,height=3)
 +        self.btn3.bind('<ButtonRelease-1>', lambda e: self.foncBoutonNumerique(3))
 +        self.btn4 = Button(principale, text = '4',width = 4,height=3)
 +        self.btn4.bind('<ButtonRelease-1>', lambda e: self.foncBoutonNumerique(4))
 +
 +====== CODE PAGE 11 ======
 +        self.btnDash = Button(principale, text = '-',width = 4,height=3)
 +        self.btnDash.bind('<ButtonRelease-1>', lambda e: self.foncBoutonFonction('SIGNE'))
 +        self.btnDot = Button(principale, text = '.',width = 4,height=3)
 +        self.btnDot.bind('<ButtonRelease-1>', lambda e: self.foncBoutonFonction('Dec'))
 +
 +Le bouton « btnDash » change le signe de la valeur affichée. 523 devient -523 et -523 devient 523. Le bouton btnDot saisit un point décimal. Ces exemples, ainsi que les suivants, utilisent la fonction foncBoutonFonction.
 +
 +        self.btnPlus = Button(principale,text = '+', width = 4, height=3)
 +        self.btnPlus.bind('<ButtonRelease-1>', lambda e: self.foncBoutonFonction('Ajouter'))
 +        self.btnMinus = Button(principale,text = '-', width = 4, height=3)
 +        self.btnMinus.bind('<ButtonRelease-1>', lambda e: self.foncBoutonFonction('Soustraire'))        
 +        self.btnStar = Button(principale,text = '*', width = 4, height=3)
 +        self.btnStar.bind('<ButtonRelease-1>', lambda e: self.foncBoutonFonction('Multiplier'))        
 +        self.btnDiv = Button(principale,text = '/', width = 4, height=3)
 +        self.btnDiv.bind('<ButtonRelease-1>', lambda e: self.foncBoutonFonction('Diviser'))        
 +        self.btnEqual = Button(principale, text = '=')
 +        self.btnEqual.bind('<ButtonRelease-1>', lambda e: self.foncBoutonFonction('Egal'))
 +
 +Voici les quatre boutons pour les fonctions mathématiques.
 +
 +        self.btnClear = Button(principale, text = 'EFFACER')
 +        self.btnClear.bind('<ButtonRelease-1>', lambda e: self.foncEffacer())
 +
 +Enfin, voici le bouton Effacer. Il efface bien sûr les variables et l'affichage. Maintenant nous plaçons les widgets avec la routine PlacerWidgets. D'abord nous initialisons la grille, puis nous plaçons les widgets dedans. Voici la première partie de la routine.
 +
 +    def PlacerWidgets(self,principale):
 +        principale.grid(column=0,row=0)
 +        self.lblAffichage.grid(column=0,row=0,columnspan = 4,sticky=EW)
 +        self.btn1.grid(column = 0, row = 1)
 +        self.btn2.grid(column = 1, row = 1)
 +        self.btn3.grid(column = 2, row = 1)
 +        self.btn4.grid(column = 0, row = 2)
 +        self.btn5.grid(column = 1, row = 2)
 +        self.btn6.grid(column = 2, row = 2)
 +        self.btn7.grid(column = 0, row = 3)
 +        self.btn8.grid(column = 1, row = 3)
 +        self.btn9.grid(column = 2, row = 3)
 +        self.btn0.grid(column = 1, row = 4)
 +
 +====== CODE PAGE 12 ======
 +        self.btnDash.grid(column = 0, row = 4)
 +        self.btnDot.grid(column = 2, row = 4)
 +        self.btnPlus.grid(column = 3,row = 1)
 +        self.btnMinus.grid(column = 3, row = 2)
 +        self.btnStar.grid(column = 3, row = 3)
 +        self.btnDiv.grid(column=3, row = 4)
 +        self.btnEqual.grid(column=0,row=5,columnspan = 4,sticky=NSEW)
 +        self.btnClear.grid(column=0,row=6,columnspan = 4, sticky = NSEW)
 +
 +et en dessous :
 +
 +    def foncBoutonNumerique(self,val):
 +        if self.PartieDecimale == True:
 +            self.CompteDecimales += 1
 +            self.ValeurCourante = self.ValeurCourante + (val * (10**-self.CompteDecimales))
 +        else:
 +            self.ValeurCourante = (self.ValeurCourante * 10) + val        
 +        self.Rafraichir()f.Rafraichir()
 +
 +====== CODE PAGE 13 ======
 +    def foncBoutonFonction(self,fonction):
 +        if fonction == 'Dec':
 +            self.PartieDecimale = True
 +        else:
 +            self.PartieDecimale = False
 +            self.CompteDecimales = 0
 +            if fonction == 'SIGNE':
 +                self.ValeurCourante *= -1
 +                self.Rafraichir()
 +
 +la fonction SIGNE multiplie simplement la valeur courante par -1.
 +
 +            elif fonction == 'Ajouter':
 +                self.ValeurAncienne = self.ValeurCourante
 +                self.ValeurCourante = 0
 +                self.FonctionCourante = 'Ajouter'
 +
 +La fonction Ajouter recopie « self.ValeurCourante » dans « self.ValeurAncienne », efface « self.ValeurCourante », et règle « self.FonctionCourante » à « Ajouter ». Les fonctions Soustraire, Multiplier et Diviser font la même chose avec les mots-clés appropriés.
 +
 +            elif fonction == 'Soustraire':
 +                self.ValeurAncienne = self.ValeurCourante
 +                self.ValeurCourante = 0
 +                self.FonctionCourante = 'Soustraire'
 +            elif fonction == 'Multiplier':
 +                self.ValeurAncienne = self.ValeurCourante
 +                self.ValeurCourante = 0
 +                self.FonctionCourante = 'Multiplier'
 +            elif fonction == 'Diviser':
 +                self.ValeurAncienne = self.ValeurCourante
 +                self.ValeurCourante = 0
 +                self.FonctionCourante = 'Diviser'            
 +
 +La fonction Egal est l'endroit où se produit la « magie ». Vous comprendrez facilement le code ci-dessous maintenant.
 +
 +            elif fonction == 'Egal':
 +                if self.FonctionCourante == 'Ajouter':
 +                    self.ValeurCourante += self.ValeurAncienne
 +                elif self.FonctionCourante == 'Soustraire':
 +                    self.ValeurCourante = self.ValeurAncienne - self.ValeurCourante
 +                elif self.FonctionCourante == 'Multiplier':
 +                    self.ValeurCourante *= self.ValeurAncienne
 +                elif self.FonctionCourante == 'Diviser':
 +                    self.ValeurCourante = self.ValeurAncienne / self.ValeurCourante
 +                self.Rafraichir()
 +                self.ValeurCourante = 0
 +                self.ValeurAncienne = 0
  
issue51/python_partie_25_pp._7-14.1314538670.txt.gz · Dernière modification : 2011/08/28 15:37 de andre_domenech