Outils pour utilisateurs

Outils du site


issue58:tuto_python

This month, we'll explore yet another GUI designer, this time for Tkinter. Many people have an issue with Tkinter because it doesn't offer a built-in designer. While I've shown you how to easily design your applications without a designer, we will examine one now. It's called Page. Basically it's a version of Visual TCL with Python support on top. The current version is 3.2 and can be found at http://sourceforge.net/projects/page/files/latest/download. Prerequisites You need TCK/TK 8.5.4 or later, Python 2.6 or later, and pyttk - which you can get (if you don't already have it) from http://pypi.python.org/pypi/pyttk. You probably have all of these with the possible exception of pyttk.

Ce mois-ci, nous allons explorer encore un autre concepteur graphique, cette fois c'est pour Tkinter. Beaucoup de gens ont un problème avec Tkinter, car il n'offre pas un designer intégré. Alors que je vous ai montré comment concevoir facilement vos applications sans concepteur, nous allons en examiner un maintenant. Il s'appelle Page. Fondamentalement, il s'agit d'une version de Visual TCL avec une couche de Python par dessus. La version actuelle est la 3.2 et peut être trouvée à http://sourceforge.net/projects/page/files/latest/download.

Pré-requis

Vous devez avoir TCK/TK 8.5.4 ou plus, Python 2.6 ou plus et pyttk, que vous pouvez obtenir (si vous ne l'avez pas encore) à partir de http://pypi.python.org/pypi/pyttk. Vous avez probablement tous ceux-ci à l'exception possible de pyttk.

Installation You can't really ask for an easier installation routine. Simply unpack the distribution file into a folder of your choice. Run the script called “configure” from the folder where you just unpacked everything. This will create your launch script called “page” which you use to get everything going. That's it. Learning Page When you start Page, you'll get three windows (forms). One is a “launch pad”, one is a toolbox, and one shows the Attribute Editor. To start a new project, click on the Toplevel button in the toolbox. This creates your main form. You can move it wherever you wish on your screen. Next, and from now on, click on a widget in the tool box and then click where you want it on the main form. For now, let's do a button. Click on the Button button on the toolbox, and then click somewhere on the main form. Next, in the launch pad form, click on Window and select Attribute Editor (if it's not already showing). Your single button should be highlighted already, so move it around the form and when you release the mouse button you should see the position change in the attribute editor form under 'x position' and 'y position'.

Installation

Vous ne pouvez vraiment pas demander une procédure d'installation plus facile. Il suffit de décompresser le fichier de distribution dans un dossier de votre choix. Exécutez le script appelé « configure » à partir du dossier où vous venez de tout déballer. Cela va créer votre script de lancement appelé « page » que vous utiliserez pour obtenir tout le reste. C'est tout.

Apprentissage de Page

Lorsque vous démarrez Page, vous aurez trois fenêtres (formulaires). L'une est une « piste de lancement », l'autre est une boîte à outils et la dernière montre l'éditeur d'attributs.

Pour démarrer un nouveau projet, cliquez sur le bouton du haut dans la boîte à outils.

Cela crée votre formulaire principal. Vous pouvez le déplacer où vous le souhaitez sur votre écran. Ensuite, et à partir de maintenant, cliquez sur un widget dans la boîte à outils, puis cliquez sur l'endroit où vous le voulez sur le formulaire principal.

Pour l'instant, nous allons faire un bouton. Cliquez sur le bouton Button dans la boîte à outils, puis cliquez quelque part sur le formulaire principal.

Ensuite, dans le formulaire de lancement, cliquez sur Fenêtre (Window) et sélectionnez l'Éditeur d'attributs (s'il n'est pas déjà affiché). Votre bouton unique devrait être déjà mis en surbrillance ; déplacez-le dans le formulaire et lorsque vous relâchez le bouton de la souris, vous devrez voir le changement de position dans le formulaire éditeur d'attributs sous « x position » et « y position ».

Here we can set other attributes such as the text on the button (or most any other widget), the alias for the widget (the name we will refer to in our code), color, the name we will call it and more. Near the bottom of the attribute editor is the text field. This is the text that appears to the user for, in this case, the button widget. Let's change this from “button” to “Exit”. Notice that now the button says “Exit”. Now resize the form to just show the button and recenter the button in the form. Next click in the main form someplace where the button isn't. The attribute editor form now shows the attributes for the main form. Find the “title” field and change this from “New Toplevel 1” to “Test Form”.

Ici, nous pouvons définir d'autres attributs tels que le texte sur le bouton (ou la plupart des autres widgets), l'alias pour le widget (le nom auquel nous allons nous référer dans notre code), la couleur, le nom par lequel nous l'appellerons et plus. Près du bas de l'éditeur d'attributs se trouve le champ de texte. Ceci est le texte qui l'utilisateur voit pour, dans ce cas, le widget bouton. Changeons-le de « Button » à « Exit ». Remarquez que maintenant le bouton affiche « Exit ». Maintenant redimensionnez le formulaire pour montrer seulement le bouton et recentrez le bouton dans le formulaire.

Ensuite, cliquez quelque part dans le formulaire principal où le bouton n'est pas. Le formulaire éditeur d'attributs affiche maintenant les attributs du formulaire principal. Trouvez le champ « Title » et changez-le de « New Toplevel 1 » à « Test Form ».

Now, before we save our project, we need to create a folder to hold our project files. Create a folder somewhere on your drive called “PageProjects”. Now, in the launch pad window, select File then Save As. Navigate to your PageProjects folder, and, in the dialog box, type TestForm.tcl and click the Save button. Notice this is saved as a TCL file, not a Python file. We'll create the python file next. In the launch pad, find the Gen_Python menu item and click it. Select Generate Python and a new form appears. Page has generated (as the name suggests) our python code for us and placed it in a window for us to view. At the bottom of this form, are three buttons…Save, Run, and Close. Click Save. If, at this point, you were to look in your PageProjects folder, you will see the python file (TestForm.py). Now click on the Run button. In a few seconds, you'll see the project start up. The button is not connected to anything yet, so it won't do anything if you click on it. Simply close the form with the “X” in the corner of the window. Now close the Python Console window with the close button at the bottom right.

Maintenant, avant de sauvegarder notre projet, nous avons besoin de créer un dossier pour contenir nos fichiers de projet. Créez un dossier quelque part sur votre disque appelé « PageProjects ». Puis, dans la fenêtre de lancement, sélectionnez File puis Save As. Allez dans votre dossier PageProjects et, dans la boîte de dialogue, tapez TestForm.tclet et cliquez sur le bouton Save. Noter que cela est enregistré comme fichier TCL, pas comme fichier Python. Ensuite, nous allons créer le fichier python.

Dans la fenêtre de lancement, cherchez le menu Gen_Python et cliquez dessus. Sélectionnez Generate Python et un nouveau formulaire apparaît.

Page a généré (comme son nom l'indique) le code Python à notre place et l'a placé dans une fenêtre pour qu'on puisse le voir. Au bas de ce formulaire, il y a trois boutons… Save, Run et Close.

Cliquez sur Save. Si, à ce stade, vous deviez regarder dans votre dossier PageProjects, vous verriez le fichier python (TestForm.py). Maintenant, cliquez sur le bouton Run. En quelques secondes, vous verrez le projet démarrer. Le bouton n'est pas connecté à quoi que ce soit encore, il ne fera donc rien si vous cliquez dessus. Il suffit de fermer le formulaire avec le « X » dans le coin de la fenêtre. Maintenant, fermez la fenêtre de console Python avec le bouton de fermeture en bas à droite.

Back at our main form, highlight the Exit button and right click on it. Select “Bindings…”. Under the menu is a set of buttons. The first on the left allows you to create a new binding. Click on “Button-1”. This allows us to enter the binding for the left mouse button. In the window on the right, type “Button1Click”. Save and generate the python code again. Scroll down in the Python Console to the bottom of the file. Above the “class Test_Form” code is the function we just asked to be created. Notice that at this point, it simply is passed. Look further down and you'll see the code that creates and controls our button. Everything is done for us already. However, we still have to tell the button what to do. Close the Python Console and we'll continue. On the launch pad, click Window then select Function List. Here we will write our method to close the window. The first button on the left is the Add button. Click it. In the Function box, type “py:Button1Click” and, in the Arguments box, type “p1”, and change the text in the lower box to…

De retour à notre formulaire principal, sélectionnez le bouton Exit et faites un clic droit dessus. Sélectionnez « Bindings… ». Dans le menu se trouve un ensemble de boutons.

Le premier sur la gauche vous permet de créer une nouvelle liaison. Cliquez sur « Bouton-1 ». Cela nous permet de paramétrer la liaison pour le bouton gauche de la souris. Dans la fenêtre sur la droite, tapez « Button1Click ».

Enregistrez et générez le code python à nouveau. Faites défiler le code dans la console Python jusqu'à la fin du fichier. Au-dessus du code de la « class Test_Form » est la fonction dont nous venons de demander la création. Notez qu'à ce stade, il est simplement transmis. Regardez plus loin vers le bas et vous verrez le code qui crée et contrôle notre bouton. Tout est fait pour nous déjà. Toutefois, nous devons encore dire au bouton ce qu'il faut faire. Fermez la console Python et continuons.

Sur la fenêtre de lancement, cliquez sur Window puis sélectionnez Function List. Ici, nous allons écrire notre méthode pour fermer la fenêtre.

Le premier bouton à gauche est le bouton Add. Cliquez dessus. Dans la zone Function, tapez « py:Button1Click » et, dans la zone Arguments, tapez « p1 » et modifiez le texte dans la zone inférieure à …

def Button1Click(p1): sys.exit() Click on the checkmark and we are done with this. Next we have to bind this routine to the button. Select the button in the form, right click it, and select “Bindings…”. As before, click on the far left button on the toolbar and select Button-1. This is the event for the left mouse button click. In the right text box, enter “Button1Click”. Make sure you use the same case that you did for the Function we just created. Click the checkmark on the right side. Now save and generate your python code.

def Button1Click(p1):

      sys.exit()
      

Cliquez sur la coche et nous avons terminé avec cela.

Ensuite, nous devons lier cette routine au bouton. Sélectionnez le bouton dans le formulaire, faites un clic droit dessus et sélectionnez « Bindings… ». Comme précédemment, cliquez sur le bouton le plus à gauche sur la barre d'outils et sélectionnez le Button-1. C'est l'événement correspondant au clic gauche de la souris. Dans la boîte de texte à droite, entrez « Button1Click ». Assurez-vous d'utiliser la même casse que pour la fonction que nous venons de créer. Cliquez sur la coche sur le côté droit. Maintenant, sauvegardez et générez votre code python.

You should see the following code near the bottom, but OUTSIDE of the Test_Form class… def Button1Click(p1) : sys.exit() And the last line of the class should be… self.Button1.bind('<Button-1>',Button1Click) Now, if you run your code and click on the Exit button, the form should close properly.

Vous devriez voir le code suivant vers le bas, mais en dehors de la classe Test_Form…

def Button1Click(p1):

sys.exit()

Et la dernière ligne de la classe devrait être…

self.Button1.bind('<Button-1>',Button1Click)

Maintenant, si vous exécutez votre code et cliquez sur le bouton Exit, le formulaire doit se fermer correctement.

Moving Forward Now let's do something more complicated. We'll create a demo showing some of the widgets that are available. First close Page and restart it. Next, create a new Toplevel form. Add two frames, one above the other and expand them to pretty much take up the entire width of the form. In the top frame, place a label, and, using the attributes editor, change the text to “Buttons:”. Next, add two buttons along the horizontal plane. Change the text of the left one to “Normal”, and the right one to “Sunken”. While the sunken button is selected, change the relief to “sunken” and name it btnSunken. Name the “Normal” button “btnNormal”. Save this project as “Demos.tcl”. Next, place in the lower frame a label saying “Radio Buttons” and four radio buttons like in the image below. Finally, place an Exit button below the bottom frame.

Pour aller plus loin

Maintenant, nous allons faire quelque chose de plus compliqué. Nous allons créer une démo montrant quelques-uns des widgets qui sont disponibles. D'abord fermez Page et redémarrez-le. Ensuite, créez un nouveau formulaire Toplevel. Ajoutez deux cadres, l'un au-dessus de l'autre et étirez-les pour prendre à peu près toute la largeur du formulaire. Dans le cadre du haut, placez une étiquette de texte et, en utilisant l'éditeur attributs, modifiez le texte à « Buttons: ». Ensuite, ajoutez deux boutons dans le plan horizontal. Modifiez le texte de celui de gauche en « Normal » et celui de droite en « Sunken » [Ndt : en creux]. Alors que le bouton Sunken est sélectionné, changez le relief de « Sunken » et nommez-le btnSunken. Nommez le bouton « Normal » « btnNormal ». Enregistrez ce projet avec le nom « Demos.tcl ».

Ensuite, placez dans le cadre inférieur une étiquette de texte « Radio Buttons » et quatre boutons radio comme dans l'image ci-dessous. Enfin, placez un bouton Exit en dessous du cadre inférieur.

Before we work on the bindings, let's create our click functions. Open the Function List and create two functions. The first should be called btnNormalClicked and the other btnSunkenClicked. Make sure you set the arguments box to include p1. Here's the code you should have for them… def btnNormalClicked(p1): print “Normal Button Clicked” def btnSunkenClicked(p1) : print “Sunken Button Clicked” Let's add our button bindings. For each button, right click it, select “Bindings…”, and add, as before, a binding to the functions we created. For the normal button, it would be “btnNormalClicked”, and for the sunken button it would be btnSunkenClicked. Save and generate your code. Now, if you were to test the program under the “Run” option of the Python Console, and click any of the buttons, you won't see anything happen. However, when you close the application, you should see the print responses. This is normal for Page and if you simply run it from the command line as you normally do, things should work as expected.

Avant de travailler sur les liaisons, nous allons créer nos fonctions de clic. Ouvrez la liste de fonctions et créez deux fonctions. Le premier devrait être appelé btnNormalClicked et l'autre btnSunkenClicked. Assurez-vous d'inclure p1 dans la boîte d'arguments. Voici le code que vous devez avoir pour eux…

def btnNormalClicked(p1):

print “Normal Button Clicked”

def btnSunkenClicked(p1) :

print “Sunken Button Clicked”

Ajoutons nos liaisons aux boutons. Pour chaque bouton, faites un clic droit dessus, sélectionnez « Bindings… » et ajoutez, comme avant, une liaison aux fonctions que nous avons créées. Pour le bouton normal, cela sera « btnNormalClicked » et pour le bouton creux cela sera « btnSunkenClicked ». Enregistrez et générez votre code. Maintenant, si vous testiez le programme avec l'option « Run » de la console Python et cliquiez sur un des boutons, vous ne verriez rien se produire. Toutefois, lorsque vous fermerez l'application, vous devriez voir les réponses écrites. Ceci est normal pour Page et si vous l'aviez simplement exécuté à partir de la ligne de commande comme vous le feriez normalement, les choses devraient fonctionner comme prévu.

Now for our radio buttons. We have grouped them in two “clusters”. The first two (Radio 1 and Radio 2) will be cluster 1 and the other two will be cluster 2. Click on Radio1 and in the Attribute Editor, set the value to 0 and the variable to “rbc1”. Set the variable for Radio 2 to “rbc1” and the value to 1. Do the same thing for Radio 3 and Radio 4 but for both of these set the variable to “rbc2”. If you want, you can deal with the click of the radiobuttons and print something to the terminal, but for now, the important thing is that the clusters work. Clicking Radio1 will deselect Radio2 and not influence Radio3 or Radio4, and the same for Radio2 and so on. Finally, you should create a function for the Exit button, and bind it to the button like we did in the first example. If you've been following along as we have done our other Tkinter applications, you should be able to understand the code shown above right. If not, please go back a few issues for a full discussion of this code. You can see that using Page makes the basic design process much easier than doing it yourself. We've only scratched the surface of what Page can do, and we'll start doing something much more realistic next time. The python code can be found on pastebin at http://pastebin.com/qq0YVgTb.

Maintenant, passons à nos boutons radio. Nous les avons regroupés en deux groupes « clusters ». Les deux premiers (Radio 1 et Radio 2) formeront le groupe 1 et les deux autres seront le groupe 2. Cliquez sur Radio 1 et dans l'éditeur d'attributs, définissez la valeur à 0 et la variable à « rbc1 ». Définissez la variable pour Radio 2 à « rbc1 » et la valeur à 1. Faites la même chose pour Radio 3 et Radio 4, mais pour les deux réglez la variable à « rbc2 ». Si vous voulez, vous pouvez améliorer le clic des boutons radio et imprimer quelque chose dans le terminal, mais pour l'instant, la chose importante est que les groupes fonctionnent. Cliquer sur Radio1 dé-sélectionnera Radio2 et n'aura pas d'influence sur Radio3 ou Radio4, et de même pour Radio2 et ainsi de suite.

Enfin, vous devez créer une fonction pour le bouton Exit et la lier au bouton, comme nous l'avons fait dans le premier exemple.

Si vous avez suivi depuis le début nos autres applications Tkinter, vous devriez être en mesure de comprendre le code montré ci-dessus à droite. Sinon, merci de retourner dans quelques numéros précédents pour lire une présentation complète de ce code.

Vous pouvez voir qu'utiliser Page rend le processus de conception de base beaucoup plus facile que de le faire vous-même. Nous avons seulement commencé à examiner ce que peut faire Page et nous allons faire quelque chose de beaucoup plus réaliste la prochaine fois.

Le code python peut être trouvé sur pastebin à http://pastebin.com/ts3MKyCZ.

One note before we go for this month. You might have noticed that I've missed a couple of issues. This is due to my wife being diagnosed with cancer last year. As hard as I have tried to keep things from falling through the cracks, a number of things have. One of these things is my old domain/web site at www.thedesignatedgeek.com. I blew it and missed the renewal. Due to this, the domain was sold out from under me. I have set up www.thedesignatedgeek.net with all the old stuff. I will be working hard the next month to bring it all up to date. See you next time.

Une note avant de terminer pour ce mois-ci. Vous avez sans doute remarqué que j'ai manqué quelques numéros. Cela est dû au fait que ma femme a été diagnostiquée avec un cancer l'an dernier. Même si j'ai vraiment essayé d'empêcher les choses de tomber à travers les mailles du filet, un certain nombre de choses y sont passées. Une de ces choses est mon ancien domaine/site web www.thedesignatedgeek.com. J'ai fait une grossière erreur et en ai raté le renouvellement. Pour cette raison, le domaine a été vendu sans mon consentement. J'ai mis en place www.thedesignatedgeek.net avec tous les vieux trucs. Je vais travailler dur le mois prochain pour mettre tout cela à jour.

Rendez-vous la prochaine fois.

issue58/tuto_python.txt · Dernière modification : 2012/03/25 15:18 de fredphil91