issue52:tutopython
Différences
Ci-dessous, les différences entre deux révisions de la page.
Les deux révisions précédentesRévision précédenteProchaine révision | Révision précédente | ||
issue52:tutopython [2011/09/08 21:46] – fredphil91 | issue52:tutopython [2011/11/02 15:29] (Version actuelle) – corrections mineurs de participa passé ald infinitif et singulier avec s marchois | ||
---|---|---|---|
Ligne 6: | Ligne 6: | ||
Radiobuttons are considered a one of many type selection widget. It also has two options, on and off. However, they are grouped together to provide a set of options that logically can have only one selection. You can have multiple groups of Radiobuttons that, if properly programmed, won't interact with each other.** | Radiobuttons are considered a one of many type selection widget. It also has two options, on and off. However, they are grouped together to provide a set of options that logically can have only one selection. You can have multiple groups of Radiobuttons that, if properly programmed, won't interact with each other.** | ||
- | Le mois dernier, nous avons parlé de TkInter et de quatre des widgets disponibles : la fenêtre principale, les fenêtres, les boutons et les étiquettes (ou labels). Je vous ai également dit le mois dernier que je parlerai | + | Le mois dernier, nous avons parlé de TkInter et de quatre des widgets disponibles : la fenêtre principale, les fenêtres, les boutons et les étiquettes (ou labels). Je vous ai également dit le mois dernier que je parlerais |
- | Aussi, ce mois-ci, nous allons approfondir les fenêtres, les boutons et les étiquettes, | + | Aussi, ce mois-ci, nous allons approfondir les fenêtres, les boutons et les étiquettes, |
- | Les cases à cocher servent à faire plusieurs choix parmi plusieurs propositions et ont deux états : cochée ou non cochée, ou on pourrait dire aussi oui ou non. Elles sont généralement utilisées pour fournir une série d' | + | Les cases à cocher servent à faire plusieurs choix parmi plusieurs propositions et ont deux états : cochée ou non cochée, ou on pourrait dire aussi oui ou non. Elles sont généralement utilisées pour fournir une série d' |
- | Les boutons radio servent à faire un choix parmi plusieurs propositions. Ils ont aussi deux états, oui ou non. Cependant, ils sont groupés | + | Les boutons radio servent à faire un choix parmi plusieurs propositions. Ils ont aussi deux états, oui ou non. Cependant, ils sont groupés |
**A Listbox provides a list of items for the user to select from. Most times, you want the user to select only one of the items at a time, but there can be occasions that you will allow the user to select multiple items. A scroll bar can be placed either horizontally or vertically to allow the user to easily look through all the items available. | **A Listbox provides a list of items for the user to select from. Most times, you want the user to select only one of the items at a time, but there can be occasions that you will allow the user to select multiple items. A scroll bar can be placed either horizontally or vertically to allow the user to easily look through all the items available. | ||
Ligne 25: | Ligne 25: | ||
7. The final frame will have a series of buttons that will call various types of message boxes.** | 7. The final frame will have a series of buttons that will call various types of message boxes.** | ||
+ | Une ListBox fournit une liste d' | ||
+ | Notre projet consistera en une fenêtre principale et sept cadres principaux qui regrouperont visuellement nos ensembles de widgets : | ||
+ | |||
+ | 1. Le premier cadre sera très basique : il contient simplement différents labels, montrant les différentes options de mise en relief. | ||
+ | 2. Le second -plutôt simple également- contiendra des boutons qui utilisent ces mêmes options de relief. | ||
+ | 3. Dans ce cadre, nous aurons deux cases à cocher et un bouton qui inverse leur état par programmation. Elles renverront cet état (1 ou 0) à la fenêtre du terminal lorsqu' | ||
+ | 4. Ensuite, nous aurons deux groupes indépendants de trois boutons radio envoyant chacun un message à la fenêtre du terminal lorsqu' | ||
+ | 5. Celui-ci contient des champs de texte qui ne sont pas nouveaux pour vous, mais il y a aussi un bouton pour activer et désactiver l'un d'eux. Lorsqu' | ||
+ | 6. Celui-ci contient une liste avec une barre de défilement verticale qui envoie un message au terminal à chaque fois qu'un élément est sélectionné ; il aura deux boutons. Un bouton va effacer la zone de liste et l' | ||
+ | 7. Le dernier cadre contient une série de boutons qui appellent les différents types de boîtes de message. | ||
**So now, we'll start our project. Let's name it “widgetdemo1.py”. Be sure to save it because we will be writing our project in little pieces, and build on them to make our full app. Each piece revolves around one of the frames. You'll notice that I'm including a number of comments as we go, so you can refer back to what's happening. Here's the first few lines... | **So now, we'll start our project. Let's name it “widgetdemo1.py”. Be sure to save it because we will be writing our project in little pieces, and build on them to make our full app. Each piece revolves around one of the frames. You'll notice that I'm including a number of comments as we go, so you can refer back to what's happening. Here's the first few lines... | ||
Ligne 39: | Ligne 49: | ||
| | ||
- | **The first two lines (comments) are the name of the application and what we are concentrating on in this part. Line three is our import statement. Then we define our class. The next line starts our __init__ routine, which you all should be familiar with by now, but, if you are just joining us, it's the code that gets run when we instantiate the routine in the main portion of the program. We are passing it the Toplevel or root window, which comes in as master here. The last three lines (so far), call three different routines. The first (DefineVars) will set up various variables we'll need as we go. The next (BuildWidgets) will be where we define our widgets, and the last (PlaceWidgets) is where we actually place the widgets into the root window. As we did last time, we'll be using the grid geometry manager. Notice that BuildWidgets will return the object “f” (which is our root window), and we'll pass that along to the PlaceWidgets routine.** | + | Bon, maintenant nous allons commencer notre projet. Nommons-le « widgetdemo1.py ». Assurez-vous de le sauvegarder, car nous allons écrire notre projet par petits morceaux et construire notre application complète petit à petit. Chaque morceau tourne autour de l'un des cadres. Vous remarquerez que j' |
+ | # widgetdemo1.py | ||
+ | # Labels | ||
+ | from Tkinter import * | ||
+ | |||
+ | class Demo: | ||
+ | def __init__(self, | ||
+ | self.DefinirVariables() | ||
+ | f = self.ConstruireWidgets(principale) | ||
+ | self.PlacerWidgets(f) | ||
+ | |||
+ | **The first two lines (comments) are the name of the application and what we are concentrating on in this part. Line three is our import statement. Then we define our class. The next line starts our < | ||
+ | Les deux premières lignes (commentaires) sont le nom de l' | ||
** def BuildWidgets(self, | ** def BuildWidgets(self, | ||
Ligne 61: | Ligne 83: | ||
| | ||
+ | def ConstruireWidgets(self, | ||
+ | # definition de nos widgets | ||
+ | fenetre = Frame(principale) | ||
+ | # labels (ou etiquettes) | ||
+ | self.cadreLabels = Frame(fenetre, | ||
+ | | ||
+ | self.lbl1 = Label(self.cadreLabels, | ||
+ | width = 13, | ||
+ | self.lbl2 = Label(self.cadreLabels, | ||
+ | width = 13, borderwidth = 2) | ||
+ | self.lbl3 = Label(self.cadreLabels, | ||
+ | borderwidth = 2) | ||
+ | self.lbl4 = Label(self.cadreLabels, | ||
+ | width = 13, borderwidth = 2) | ||
+ | self.lbl5 = Label(self.cadreLabels, | ||
+ | width = 13, borderwidth = 2) | ||
+ | return fenetre | ||
**This is our BuildWidgets routine. Each of the lines that start with “self.” have been split for two reasons. First, it's good practice to keep the line length to 80 characters or less. Secondly, it makes it easier on our wonderful editor. You can do two things. One, just make each line long, or keep it as is. Python lets us split lines as long as they are within parentheses or brackets. As I said earlier, we are defining the widgets before we place them in the grid. You'll notice when we do the next routine, that we can also define a widget at the time we place it in the grid, but defining it before we put it in the grid in a routine like this makes it easier to keep track of everything, since we are doing (most of) the definitions in this routine. | **This is our BuildWidgets routine. Each of the lines that start with “self.” have been split for two reasons. First, it's good practice to keep the line length to 80 characters or less. Secondly, it makes it easier on our wonderful editor. You can do two things. One, just make each line long, or keep it as is. Python lets us split lines as long as they are within parentheses or brackets. As I said earlier, we are defining the widgets before we place them in the grid. You'll notice when we do the next routine, that we can also define a widget at the time we place it in the grid, but defining it before we put it in the grid in a routine like this makes it easier to keep track of everything, since we are doing (most of) the definitions in this routine. | ||
Ligne 67: | Ligne 105: | ||
So, first we define our master frame. This is where we will be putting the rest of our widgets. Next, we define a child (of the master frame) frame that will hold five labels, and call it lblframe. We set the various attributes of the frame here. We set the relief to ' | So, first we define our master frame. This is where we will be putting the rest of our widgets. Next, we define a child (of the master frame) frame that will hold five labels, and call it lblframe. We set the various attributes of the frame here. We set the relief to ' | ||
+ | Voici notre routine ConstruireWidgets. Les lignes qui commence par « self. » ont été coupées pour deux raisons. Tout d' | ||
+ | Nous définissons donc d' | ||
- | **Next, we define each label widget that we will use. We set the parent as self.lblframe, | + | **Next, we define each label widget that we will use. We set the parent as self.lblframe, |
Here's our PlaceWidgets routine... | Here's our PlaceWidgets routine... | ||
Ligne 87: | Ligne 127: | ||
| | ||
+ | Ensuite, nous définissons chaque widget étiquette que nous allons utiliser. Nous fixons le parent à self.cadreLabels, | ||
+ | Voici notre routine PlacerWidgets... | ||
+ | |||
+ | def PlacerWidgets(self, | ||
+ | fenetre = principale | ||
+ | # place les widgets | ||
+ | fenetre.grid(column = 0, row = 0) | ||
+ | # place les labels | ||
+ | self.cadreLabels.grid(column = 0, row = 1, padx = 5, pady = 5, | ||
+ | columnspan = 5, | ||
+ | l = Label(self.cadreLabels, | ||
+ | anchor=' | ||
+ | self.lbl1.grid(column = 1, row = 0, padx = 3, pady = 5) | ||
+ | self.lbl2.grid(column = 2, row = 0, padx = 3, pady = 5) | ||
+ | self.lbl3.grid(column = 3, row = 0, padx = 3, pady = 5) | ||
+ | self.lbl4.grid(column = 4, row = 0, padx = 3, pady = 5) | ||
+ | self.lbl5.grid(column = 5, row = 0, padx = 3, pady = 5) | ||
**We get the frame object in as a parameter called master. We assign that to ' | **We get the frame object in as a parameter called master. We assign that to ' | ||
Ligne 93: | Ligne 150: | ||
Next, we lay out all of our other labels in the grid - starting at column 1, row 0.** | Next, we lay out all of our other labels in the grid - starting at column 1, row 0.** | ||
+ | Nous récupérons l' | ||
+ | Ensuite, nous plaçons toutes nos autres étiquettes dans la grille, à partir de la colonne 1, ligne 0. | ||
**Here is our DefineVars routine. Notice that we simply use the pass statement for now. We'll be filling it in later on, and we don't need it for this part: | **Here is our DefineVars routine. Notice that we simply use the pass statement for now. We'll be filling it in later on, and we don't need it for this part: | ||
Ligne 108: | Ligne 167: | ||
root.mainloop()** | root.mainloop()** | ||
+ | Voici notre routine DefinirVariables. Notez que nous utilisons simplement l' | ||
+ | def DefinirVariables(self): | ||
+ | # definit nos ressources | ||
+ | pass | ||
+ | Et enfin nous plaçons notre code pour la routine principale : | ||
+ | racine = Tk() | ||
+ | racine.geometry(' | ||
+ | racine.title(" | ||
+ | demo = Demo(racine) | ||
+ | | ||
+ | racine.mainloop() | ||
**First, we instantiate an instance of Tk. Thern we set the size of the main window to 750 pixels wide by 40 pixels high, and locate it at 150 pixels from the left and top of the screen. Then we set the title of the window and instantiate our Demo object, and finally call the Tk mainloop. | **First, we instantiate an instance of Tk. Thern we set the size of the main window to 750 pixels wide by 40 pixels high, and locate it at 150 pixels from the left and top of the screen. Then we set the title of the window and instantiate our Demo object, and finally call the Tk mainloop. | ||
Ligne 116: | Ligne 186: | ||
Now save what you have as widgetdemo1a.py, | Now save what you have as widgetdemo1a.py, | ||
+ | D' | ||
+ | |||
+ | Essayez. Vous devriez voir les cinq étiquettes ainsi que l' | ||
+ | |||
+ | Les boutons | ||
+ | Maintenant, enregistrez ce que vous avez en tant que widgetdemo1a.py et nous ajoutons quelques boutons. Puisque nous avons construit notre programme de base ainsi, nous allons simplement pouvoir y ajouter les parties qui manquent. Commençons par la routine ConstruireWidgets. Après les définitions des étiquettes, | ||
** # Buttons | ** # Buttons | ||
Ligne 137: | Ligne 213: | ||
| | ||
+ | # boutons | ||
+ | self.cadreBoutons = Frame(fenetre, | ||
+ | pady = 3, borderwidth = 2, width = 500) | ||
+ | self.btn1 = Button(self.cadreBoutons, | ||
+ | | ||
+ | self.btn2 = Button(self.cadreBoutons, | ||
+ | | ||
+ | self.btn3 = Button(self.cadreBoutons, | ||
+ | | ||
+ | self.btn4 = Button(self.cadreBoutons, | ||
+ | | ||
+ | self.btn5 = Button(self.cadreBoutons, | ||
+ | | ||
+ | self.btn1.bind('< | ||
+ | self.btn2.bind('< | ||
+ | self.btn3.bind('< | ||
+ | self.btn4.bind('< | ||
+ | self.btn5.bind('< | ||
**Nothing really new here. We've defined the buttons, with their attributes, and set their callbacks via the .bind configuration. Notice that we are using lambda to send the values 1 through 5 based on which button is clicked. In the callback, we'll use that so we know which button we are dealing with. Now we'll work in the PlaceWidgets routine. Put the following code right after the last label placement: | **Nothing really new here. We've defined the buttons, with their attributes, and set their callbacks via the .bind configuration. Notice that we are using lambda to send the values 1 through 5 based on which button is clicked. In the callback, we'll use that so we know which button we are dealing with. Now we'll work in the PlaceWidgets routine. Put the following code right after the last label placement: | ||
Ligne 151: | Ligne 244: | ||
| | ||
+ | Rien de bien nouveau ici. Nous avons défini les boutons avec leurs attributs et avons fixé leurs fonctions de rappel avec un « .bind ». Notez que nous utilisons lambda pour envoyer les valeurs 1 à 5 suivant le bouton sur lequel on clique. Dans la fonction de rappel, nous allons utiliser cela afin de savoir quel bouton on doit gérer. Maintenant, nous allons travailler dans la routine PlacerWidgets. Placez le code suivant juste après l' | ||
+ | # place les boutons | ||
+ | self.cadreBoutons.grid(column=0, | ||
+ | pady = 5, columnspan = 5,sticky = ' | ||
+ | l = Label(self.cadreBoutons, | ||
+ | anchor=' | ||
+ | self.btn1.grid(column = 1, row = 0, padx = 3, pady = 3) | ||
+ | self.btn2.grid(column = 2, row = 0, padx = 3, pady = 3) | ||
+ | self.btn3.grid(column = 3, row = 0, padx = 3, pady = 3) | ||
+ | self.btn4.grid(column = 4, row = 0, padx = 3, pady = 3) | ||
+ | self.btn5.grid(column = 5, row = 0, padx = 3, pady = 3) | ||
**Once again, nothing really new here, so we'll move on. Here's our callback routine. Put it after the DefineVars routine: | **Once again, nothing really new here, so we'll move on. Here's our callback routine. Put it after the DefineVars routine: | ||
Ligne 166: | Ligne 269: | ||
| | ||
+ | Une fois de plus, rien de vraiment nouveau ici, donc nous allons continuer. Voici notre routine de rappel. Placez-la après la routine DefinirVariables : | ||
+ | def clicBouton(self, | ||
+ | if val == 1: | ||
+ | print(" | ||
+ | elif val == 2: | ||
+ | print(" | ||
+ | elif val == 3: | ||
+ | print(" | ||
+ | elif val == 4: | ||
+ | print(" | ||
+ | elif val == 5: | ||
+ | print(" | ||
**Again, nothing really fancy here. We just use a series of IF/ELIF routines to print what button was clicked. The main thing to look at here (when we run the program) is that the sunken button doesn' | **Again, nothing really fancy here. We just use a series of IF/ELIF routines to print what button was clicked. The main thing to look at here (when we run the program) is that the sunken button doesn' | ||
Ligne 175: | Ligne 289: | ||
Now save this as widgetdemo1b.py, | Now save this as widgetdemo1b.py, | ||
+ | Encore une fois, rien de vraiment sensationnel ici. Nous utilisons simplement une série de routines IF/ELIF pour afficher quel bouton a été cliqué. La principale chose à regarder ici (lorsque nous exécutons le programme) est que le bouton « en creux » ne bouge pas lorsqu' | ||
+ | root.geometry (' | ||
+ | |||
+ | Ok. C'est terminé pour celui-ci. Enregistrez-le et lancez-le. | ||
+ | Maintenant sauvegardez ceci comme widgetdemo1b.py et nous allons passer aux cases à cocher. | ||
**Checkboxes | **Checkboxes | ||
As I said earlier, this part of the demo has a normal button and two checkboxes. The first checkbox is what you would normally expect a checkbox to look like. The second is more like a “sticky” button - when it's not selected (or checked), it looks like a normal button. When you select it, it looks like a button that is stuck down. We can do this by simply setting the indicatoron attribute to False. The “normal” button will toggle the checkboxes from checked to unchecked, and vice versa, each time you click the button. We get to do this programmatically by calling the .toggle method attached to the checkbox. We bind the left mouse button click event (button release) to a function so we can send a message (in this case) to the terminal. In addition to all of this, we are setting two variables (one for each of the checkboxes) that we can query at any time. In this case, each time the checkbox is clicked we query this value and print it. Pay attention to the variable portion of the code. It is used in many widgets.** | As I said earlier, this part of the demo has a normal button and two checkboxes. The first checkbox is what you would normally expect a checkbox to look like. The second is more like a “sticky” button - when it's not selected (or checked), it looks like a normal button. When you select it, it looks like a button that is stuck down. We can do this by simply setting the indicatoron attribute to False. The “normal” button will toggle the checkboxes from checked to unchecked, and vice versa, each time you click the button. We get to do this programmatically by calling the .toggle method attached to the checkbox. We bind the left mouse button click event (button release) to a function so we can send a message (in this case) to the terminal. In addition to all of this, we are setting two variables (one for each of the checkboxes) that we can query at any time. In this case, each time the checkbox is clicked we query this value and print it. Pay attention to the variable portion of the code. It is used in many widgets.** | ||
+ | Les cases à cocher | ||
+ | Comme je l'ai dit précédemment, | ||
**Under the BuildWidget routine, after the button code we just put in and before the return statement, put the following code: | **Under the BuildWidget routine, after the button code we just put in and before the return statement, put the following code: | ||
Ligne 195: | Ligne 316: | ||
| | ||
+ | Dans la routine ConstruireWidgets, | ||
+ | # checkbox (ou cases a cocher) | ||
+ | self.cadreCases = Frame(fenetre, | ||
+ | borderwidth = 2, width = 500) | ||
+ | self.chk1 = Checkbutton(self.cadreCases, | ||
+ | variable=self.Chk1Val) | ||
+ | self.chk2 = Checkbutton(self.cadreCases, | ||
+ | variable=self.Chk2Val, | ||
+ | self.chk1.bind('< | ||
+ | self.chk2.bind('< | ||
+ | self.btnInverserCases = Button(self.cadreCases, | ||
+ | self.btnInverserCases.bind('< | ||
**Again, you have seen all of this before. We create the frame to hold our widgets. We set up a button and two check boxes. Let's place them now: | **Again, you have seen all of this before. We create the frame to hold our widgets. We set up a button and two check boxes. Let's place them now: | ||
Ligne 207: | Ligne 339: | ||
| | ||
+ | Encore une fois, vous avez vu tout cela avant. Nous créons le cadre pour contenir nos widgets. Nous créons un bouton et deux cases à cocher. Plaçons-les maintenant : | ||
+ | # place les cases à cocher et le bouton d' | ||
+ | self.cadreCases.grid(column = 0, row = 3, padx = 5, pady = 5, | ||
+ | | ||
+ | l = Label(self.cadreCases, | ||
+ | anchor=' | ||
+ | self.btnInverserCases.grid(column = 1, row = 0, padx = 3, pady = 3) | ||
+ | self.chk1.grid(column = 2, row = 0, padx = 3, pady = 3) | ||
+ | self.chk2.grid(column = 3, row = 0, padx = 3, pady = 3) | ||
**Now we define the two variables that we will use to monitor the value of each check box. Under DefineVars, comment out the pass statement, and add this... | **Now we define the two variables that we will use to monitor the value of each check box. Under DefineVars, comment out the pass statement, and add this... | ||
Ligne 226: | Ligne 366: | ||
| | ||
+ | Maintenant, nous définissons les deux variables que nous allons utiliser pour surveiller la valeur de chaque case à cocher. Sous DefinirVariables, | ||
+ | self.Chk1Val = IntVar () | ||
+ | self.Chk2Val = IntVar () | ||
+ | Après la fonction de rappel des boutons, placez ce qui suit... | ||
+ | def btnInverser(self, | ||
+ | self.chk1.toggle() | ||
+ | self.chk2.toggle() | ||
+ | print(" | ||
+ | print(" | ||
**And finally replace the geometry statement with this... | **And finally replace the geometry statement with this... | ||
Ligne 235: | Ligne 384: | ||
If you are old enough to remember car radios with push buttons to select the station presets, you'll understand why these are called Radiobuttons. When using radiobuttons, | If you are old enough to remember car radios with push buttons to select the station presets, you'll understand why these are called Radiobuttons. When using radiobuttons, | ||
+ | Et enfin remplacez l' | ||
+ | root.geometry (' | ||
+ | |||
+ | Enregistrez et exécutez. Enregistrez-le comme widgetdemo1c.py et continuons avec les boutons radio. | ||
+ | |||
+ | Les boutons radio | ||
+ | Si vous êtes assez vieux pour vous souvenir des autoradios avec boutons poussoirs pour sélectionner les stations préréglées, | ||
**Back to BuildWidgets, | **Back to BuildWidgets, | ||
Ligne 253: | Ligne 409: | ||
| | ||
+ | Retournez dans ConstruireWidgets, | ||
+ | # boutons radio | ||
+ | self.cadreBoutonsRadio = Frame(fenetre, | ||
+ | self.rb1 = Radiobutton(self.cadreBoutonsRadio, | ||
+ | self.rb2 = Radiobutton(self.cadreBoutonsRadio, | ||
+ | self.rb3 = Radiobutton(self.cadreBoutonsRadio, | ||
+ | self.rb1.bind('< | ||
+ | self.rb2.bind('< | ||
+ | self.rb3.bind('< | ||
+ | self.rb4 = Radiobutton(self.cadreBoutonsRadio, | ||
+ | self.rb5 = Radiobutton(self.cadreBoutonsRadio, | ||
+ | self.rb6 = Radiobutton(self.cadreBoutonsRadio, | ||
+ | self.rb4.bind('< | ||
+ | self.rb5.bind('< | ||
+ | self.rb6.bind('< | ||
**In PlaceWidgets, | **In PlaceWidgets, | ||
Ligne 273: | Ligne 443: | ||
| | ||
+ | Ajoutez ceci dans PlacerWidgets : | ||
+ | # place les boutons radio et selectionne le premier | ||
+ | self.cadreBoutonsRadio.grid(column = 0, row = 4, padx = 5, pady = 5, columnspan = 5,sticky = ' | ||
+ | l = Label(self.cadreBoutonsRadio, | ||
+ | text=' | ||
+ | width=15, | ||
+ | self.rb1.grid(column = 2, row = 0, padx = 3, pady = 3, sticky = ' | ||
+ | self.rb2.grid(column = 3, row = 0, padx = 3, pady = 3, sticky = ' | ||
+ | self.rb3.grid(column = 4, row = 0, padx = 3, pady = 3, sticky = ' | ||
+ | self.RBVal.set(" | ||
+ | l = Label(self.cadreBoutonsRadio, | ||
+ | width = 15, | ||
+ | anchor = ' | ||
+ | self.rb4.grid(column = 6, row = 0) | ||
+ | self.rb5.grid(column = 7, row = 0) | ||
+ | self.rb6.grid(column = 8, row = 0) | ||
+ | self.RBVal2.set(" | ||
**One thing of note here. Notice the “last minute” label definitions in the PlaceWidget routine. These long lines are broken up to show how to use parens to allow our long lines to be formatted nicely in our code, and still function correctly. | **One thing of note here. Notice the “last minute” label definitions in the PlaceWidget routine. These long lines are broken up to show how to use parens to allow our long lines to be formatted nicely in our code, and still function correctly. | ||
Ligne 289: | Ligne 475: | ||
root.geometry(' | root.geometry(' | ||
+ | Une chose à noter ici. Remarquez les définitions de « dernière minute » pour les étiquettes dans la routine PlacerWidgets. Ces lignes longues sont coupées pour montrer comment utiliser les parenthèses pour permettre à nos longues lignes d' | ||
+ | |||
+ | Dans DefinirVariables, | ||
+ | self.RBVal = IntVar () | ||
+ | |||
+ | Ajoutez les routines de clics : | ||
+ | def clicBoutonRadio(self): | ||
+ | print(" | ||
+ | def clicBoutonRadio2(self): | ||
+ | print(" | ||
+ | et enfin modifiez à nouveau la géométrie comme ceci. | ||
+ | root.geometry (' | ||
**Save the project as widgetdemo1d.py, | **Save the project as widgetdemo1d.py, | ||
Ligne 301: | Ligne 499: | ||
| | ||
+ | Enregistrez le projet sous widgetdemo1d.py et exécutez-le. Maintenant, nous allons travailler sur les champs de texte standard (ou widgets de saisie). | ||
+ | Les champs de texte | ||
+ | |||
+ | Encore une fois, nous avons déjà utilisé des champs de texte (ou widgets de saisie) dans diverses interfaces graphiques auparavant. Mais cette fois-ci, comme je l'ai dit précédemment, | ||
+ | # champs de texte | ||
+ | self.cadreChampsTexte = Frame(fenetre, | ||
+ | self.txt1 = Entry(self.cadreChampsTexte, | ||
+ | self.txt2 = Entry(self.cadreChampsTexte, | ||
+ | self.btnDesactiver = Button(self.cadreChampsTexte, | ||
+ | self.btnDesactiver.bind('< | ||
**Next, add this code to the PlaceWidget routine: | **Next, add this code to the PlaceWidget routine: | ||
Ligne 314: | Ligne 522: | ||
self.Disabled = False** | self.Disabled = False** | ||
+ | Ensuite, ajoutez le code à la routine PlacerWidgets : | ||
+ | # place les champs de texte | ||
+ | self.cadreChampsTexte.grid(column = 0, row = 5, padx = 5, pady = 5, columnspan = 5,sticky = ' | ||
+ | l = Label(self.cadreChampsTexte, | ||
+ | self.txt1.grid(column = 2, row = 0, padx = 3, pady = 3) | ||
+ | self.txt2.grid(column = 3, row = 0, padx = 3, pady = 3) | ||
+ | self.btnDesactiver.grid(column = 1, row = 0, padx = 3, pady = 3) | ||
+ | Ajoutez cette ligne en bas de la routine DefinirVariables : | ||
+ | self.Disabled = False | ||
**Now, add the function that responds to the button click event: | **Now, add the function that responds to the button click event: | ||
Ligne 328: | Ligne 545: | ||
root.geometry(' | root.geometry(' | ||
+ | Maintenant ajoutez la fonction qui répond au clic sur le bouton : | ||
+ | def clicBoutonDesactiver(self, | ||
+ | if self.Disabled == False: | ||
+ | self.Disabled = True | ||
+ | self.txt2.configure(state=' | ||
+ | else: | ||
+ | self.Disabled = False | ||
+ | self.txt2.configure(state=' | ||
+ | Reconfigurer les dimensions à : | ||
+ | root.geometry(' | ||
**Save it as widgetdemo1d.py, | **Save it as widgetdemo1d.py, | ||
Ligne 347: | Ligne 574: | ||
| | ||
+ | Sauvegardez-le sous le nom widgetdemo1d.py et exécutez-le. | ||
+ | |||
+ | Les listes | ||
+ | |||
+ | Ensuite nous allons travailler sur les listes. En commençant dans ConstruireWidgets, | ||
+ | # Données pour la liste | ||
+ | self.cadreListe = Frame(fenetre, | ||
+ | relief = SUNKEN, | ||
+ | padx = 3, | ||
+ | pady = 3, | ||
+ | borderwidth = 2, | ||
+ | width = 500 | ||
+ | ) | ||
+ | # boite avec barre de défilement pour la liste | ||
+ | self.defilementV = Scrollbar(self.cadreListe) | ||
+ | self.liste = Listbox(self.cadreListe, | ||
+ | | ||
+ | | ||
** # default height is 10 | ** # default height is 10 | ||
Ligne 367: | Ligne 612: | ||
| | ||
+ | # hauteur par defaut = 10 | ||
+ | self.liste.bind('<< | ||
+ | self.defilementV.config(command = self.liste.yview) | ||
+ | self.btnEffacerListe = Button( | ||
+ | | ||
+ | text = " | ||
+ | | ||
+ | width = 11 | ||
+ | ) | ||
+ | self.btnRemplirListe = Button( | ||
+ | | ||
+ | text = " | ||
+ | | ||
+ | width = 11 | ||
+ | ) | ||
+ | # << | ||
+ | # remplit la liste | ||
+ | self.remplirListe() | ||
**As usual, we create our frame. Then we create our vertical scroll bar. We do this before we create the list box, because we have to reference the scrollbar ' | **As usual, we create our frame. Then we create our vertical scroll bar. We do this before we create the list box, because we have to reference the scrollbar ' | ||
Ligne 380: | Ligne 642: | ||
| | ||
+ | Comme d' | ||
+ | Maintenant, nous allons nous occuper du code supplémentaire dans la routine PlacerWidgets : | ||
+ | # place la liste et les boutons associes | ||
+ | self.cadreListe.grid(column = 0, row = 6, padx = 5, pady = 5, columnspan = 5,sticky = ' | ||
+ | l = Label(self.cadreListe, | ||
+ | self.liste.grid(column = 2, row = 0, | ||
+ | self.defilementV.grid(column = 3, row = 0,rowspan = 2, sticky = ' | ||
+ | self.btnEffacerListe.grid(column = 1, row = 0, padx = 5) | ||
+ | self.btnRemplirListe.grid(column = 1, row = 1, padx = 5) | ||
**In DefineVars add this... | **In DefineVars add this... | ||
Ligne 396: | Ligne 667: | ||
# insert([0, | # insert([0, | ||
+ | Ajoutez ceci dans DefinirVariables : | ||
+ | # les elements pour notre liste | ||
+ | self.exemples = [' | ||
+ | Et ajoutez les routines de support suivantes : | ||
+ | def effacerListe(self): | ||
+ | self.liste.delete(0, | ||
+ | | ||
+ | def remplirListe(self): | ||
+ | # Note : effacer d' | ||
+ | for ex in self.exemples: | ||
+ | self.liste.insert(END, | ||
+ | # insert([0, | ||
** def LBoxSelect(self, | ** def LBoxSelect(self, | ||
Ligne 408: | Ligne 691: | ||
root.geometry(' | root.geometry(' | ||
+ | def listeSelection(self, | ||
+ | print(" | ||
+ | items = self.liste.curselection() | ||
+ | selitem = items[0] | ||
+ | print(" | ||
+ | print(" | ||
+ | Enfin, mettez à jour la ligne de géométrie : | ||
+ | root.geometry(' | ||
**Save this as widgetdemo1e.py, | **Save this as widgetdemo1e.py, | ||
Ligne 426: | Ligne 717: | ||
| | ||
+ | Sauvegarder cela comme widgetdemo1e.py et exécutez-le. Maintenant, nous allons faire les dernières modifications à notre application. | ||
+ | Les boîtes de dialogue | ||
+ | |||
+ | Cette section est tout simplement une série de boutons « normaux » qui appellent les différents types de boîtes de dialogue. Nous les avons déjà rencontrés avec une boîte à outils différente. Nous allons explorer seulement 5 types différents, | ||
+ | # boutons pour afficher les fenetres de messages et de dialogues | ||
+ | self.cadreMessages = Frame(fenetre, | ||
+ | self.btnMBInfo = Button(self.cadreMessages, | ||
+ | self.btnMBWarning = Button(self.cadreMessages, | ||
+ | self.btnMBError = Button(self.cadreMessages, | ||
+ | self.btnMBQuestion = Button(self.cadreMessages, | ||
+ | self.btnMBYesNo = Button(self.cadreMessages, | ||
+ | self.btnMBInfo.bind('< | ||
+ | self.btnMBWarning.bind('< | ||
+ | self.btnMBError.bind('< | ||
+ | self.btnMBQuestion.bind('< | ||
+ | self.btnMBYesNo.bind('< | ||
**Now, add the code for the PlaceWidgets routine: | **Now, add the code for the PlaceWidgets routine: | ||
Ligne 438: | Ligne 745: | ||
| | ||
+ | Maintenant ajoutez le code dans la routine PlacerWidgets : | ||
+ | # boutons de boîtes de messages et cadre | ||
+ | self.cadreMessages.grid(column = 0,row = 7, columnspan = 5, padx = 5, sticky = ' | ||
+ | l = Label(self.cadreMessages, | ||
+ | self.btnMBInfo.grid(column = 1, row = 0, padx= 3) | ||
+ | self.btnMBWarning.grid(column = 2, row = 0, padx= 3) | ||
+ | self.btnMBError.grid(column = 3, row = 0, padx= 3) | ||
+ | self.btnMBQuestion.grid(column = 4, row = 0, padx= 3) | ||
+ | self.btnMBYesNo.grid(column = 5, row = 0, padx= 3) | ||
**Here is the support routine. For the first three (Info, Warning, and Error), you simply call ' | **Here is the support routine. For the first three (Info, Warning, and Error), you simply call ' | ||
Ligne 455: | Ligne 770: | ||
| | ||
+ | Voici la routine d' | ||
+ | def afficheFenetreMessage(self, | ||
+ | if which == 1: | ||
+ | tkMessageBox.showinfo(' | ||
+ | elif which == 2: | ||
+ | tkMessageBox.showwarning(' | ||
+ | elif which == 3: | ||
+ | tkMessageBox.showerror(' | ||
+ | elif which == 4: | ||
+ | rep = tkMessageBox.askquestion(' | ||
+ | print(' | ||
+ | elif which == 5: | ||
+ | rep = tkMessageBox.askyesno(' | ||
+ | print(' | ||
**Finally, modify the geometry line: | **Finally, modify the geometry line: | ||
Ligne 466: | Ligne 794: | ||
That's it for this time. I hope this has inspired you to explore all of the goodies that tkinter provides. See you next time.** | That's it for this time. I hope this has inspired you to explore all of the goodies that tkinter provides. See you next time.** | ||
- | version française | + | Enfin, modifiez la ligne de géométrie |
- | http:// | + | |
+ | |||
+ | Sauvegardez ceci sous le nom widgetdemo1f.py et amusez-vous avec. | ||
+ | |||
+ | J'ai placé le code de widgetdemo1f.py sur pastebin ici : http:// | ||
+ | |||
+ | C'est tout pour cette fois. J' | ||
issue52/tutopython.1315511186.txt.gz · Dernière modification : 2011/09/08 21:46 de fredphil91