Outils pour utilisateurs

Outils du site


issue65:python

Titre : Programming in Python – Part 37

Programmer en Python. Partie 37.

This month, we’ll finish up the transposer program that we wrote in Kivy. Hopefully, you saved the code from last time, because we’ll be building upon it. If not, grab the code from FCM#64. Let’s start by recapping what we did last month. We created an application that allows for a guitarist to quickly transpose from one key to the other. The ultimate goal is to be able to run this app not only on your Linux or Windows box, but on an android device as well. I take mine on my tablet whenever I go to band practice. I was going to deal with packaging our project for Android, but some things have changed in the method to do that, so we’ll work on that next month. The app, as we left it last time, looked like that shown below left. When we are done, it should look like the screen below right.

Ce mois-ci, nous allons terminer le programme de transposition que nous avons écrit dans Kivy. J'espère que vous avez enregistré le code de la dernière fois, parce que nous allons le compléter. Sinon, récupérez-le sur le FCM n°64.

Commençons par récapituler ce que nous avons fait le mois dernier. Nous avons créé une application qui permet à un guitariste de transposer rapidement d'une clé à une autre. Le but ultime est de pouvoir exécuter cette application non seulement sous Linux ou Windows, mais également sur un appareil Android. Je l'emporte sur ma tablette quand je vais répéter avec mon groupe. Je me préparais à conditionner notre projet pour Android, mais certaines choses ont changé dans la méthode pour le faire, nous verrons donc cela le mois prochain.

L'application, telle que nous l'avons laissée la dernière fois, ressemblait à ce qui est ci-dessous à gauche.

Lorsque nous aurons terminé, elle devrait ressembler à l'écran ci-dessous à droite.

The first thing you will notice is that there are blue labels rather than boring gray ones. The next is that there are three buttons. Finally the scrollable labels are closer to the entire width of the window. Other than that, it’s pretty much (visually) the same. One of the buttons is an “about” button that will pop up simple information, but it explains how to make a simple popup. One of the buttons is an exit button. The other button will swap the label text to make it easy to transpose from piano to guitar or guitar to piano. Let’s get started by creating a .kv file (above right). This is what will give us the colored labels. It’s a very simple file. The first two lines are required. They basically say what version of Kivy to expect. Next we create a new type of label called ‘BoundedLabel’. The color is set with RGB values (between 0 and 1, which can be considered as 100 percent), and as you can see the blue value is set at 100 percent. We will also create a rectangle which is the actual label. Save this as “transpose.kv”. You must use the name of the class that will be using it.

La première chose que vous remarquerez est qu'il y a des étiquettes bleues à la place de celles qui étaient grises et tristes. La suivante est qu'il y a trois boutons. Enfin, les étiquettes qui défilent sont plus proches de la largeur totale de la fenêtre. À part ça, c'est à peu près la même chose (visuellement). L'un des boutons est un bouton « à propos » qui affichera quelques informations simples, pour vous montrer comment faire un pop-up simple. Un autre bouton sert à quitter. Le troisième bouton va remplacer l'étiquette de texte pour faciliter la transposition de piano à guitare ou vice-versa.

Nous allons commencer par créer un fichier .kv (en haut à droite). C'est ce qui va nous donner les étiquettes colorées. C'est un fichier très simple.

Les deux premières lignes sont nécessaires. Elles indiquent simplement quelle version de Kivy est requise. Ensuite, nous créons un nouveau type d'étiquette appelé « BoundedLabel ». La couleur est réglée avec des valeurs RVB (entre 0 et 1, ce dernier représentant 100 % ), et comme vous pouvez le voir, la valeur de bleu est fixée à 100 pour cent. Nous allons également créer un rectangle qui est l'étiquette réelle. Enregistrez ce fichier sous le nom « transpose.kv ». Vous devez prendre le même nom que la classe qui va l'utiliser.

Now that you have that completed, add the following lines just before the transpose class to the source file from last time: class BoundedLabel(Label): pass To make it work, all we need is a definition. Before we go any further, add the following line to the import section: from kivy.uix.popup import Popup

Maintenant que ceci est terminé, ajoutez les lignes suivantes juste avant la classe transpose dans le fichier source de la dernière fois :

class BoundedLabel(Label):
pass

Pour que cela fonctionne, il suffit d'une définition. Avant d'aller plus loin, ajoutez la ligne suivante à la section des importations :

from kivy.uix.popup import Popup

This allows us to create the popup later on. Now, in the Transpose class, just inside the def build routine, place the code shown above right. The LoadLabels routine will give us the colored labels (BoundedLabel) and the swap ability. You saw most of this last time. We pass a value to the “w” parameter to determine which text is being displayed. The l=BoundedLabel line is pretty much the same line from last time, with the exception that, this time, we are using a BoundedLabel widget instead of a Button widget. The LoadLabels will mainly be called from the next routine, Swap. Place this code (shown right) below LoadLabels. You can see that this routine is pretty self explanatory. We use a variable (self.whichway) to determine “which way” the labels are displaying… from Guitar to Piano or Piano to Guitar. Be sure to save your work at this point, since we are going to be making a lot of changes from here on.

Cela nous permet de créer la popup plus tard. Maintenant, dans la classe Transpose, juste à l'intérieur de la routine build, placez le code ci-dessus à droite.

La routine ChargeEtiquettes nous donnera les étiquettes de couleur (BoundedLabel) et la capacité d'échange. Vous avez pratiquement tout vu la dernière fois. Nous passons une valeur au paramètre « w » pour déterminer quel texte est affiché. La ligne l=BoundedLabel est à peu près la même que la dernière fois, sauf que, cette fois, nous utilisons un widget BoundedLabel au lieu d'un widget Bouton. Les « ChargeEtiquettes » seront principalement appelés depuis la routine suivante, Echanger. Placez ce code (à droite) en dessous de ChargeEtiquettes.

Vous pouvez voir que cette routine est assez explicite. Nous utilisons une variable (self.quelsens) pour déterminer « dans quel sens » les étiquettes s'affichent… de Guitare vers Piano ou de Piano vers Guitare.

Assurez-vous de sauvegarder votre travail maintenant, car nous allons faire beaucoup de changements à partir de maintenant.

Replace the lines defining text1 and text two with the lines shown above. We set self.whichway to 0 which will be our default for the swap procedure. Then we define four strings instead of the two we had last time. You might notice that strings text3 and text4 are simple reversals of text1 and text2. Now we will tweak the root line definition. Change it from… root = GridLayout(orientation='vertical', spacing=10, cols=1,rows=3) to root = GridLayout(orientation='vertical', spacing=6, cols=1, rows=4, row_default_height=40) We’ve changed the spacing from 10 to 6 and set the default row height to 40 pixels. Change the text for the label (next line) to “text='Transposer Ver 0.8.0'”. Everything else stays the same on this line.

Remplacez les lignes définissant texte1 et texte2 avec les lignes ci-dessus.

Nous réglons self.quelsens à 0 qui sera notre valeur par défaut pour la procédure d'échange. Ensuite, nous définissons quatre chaînes au lieu des deux que nous avions la dernière fois. Vous remarquerez peut-être que les chaînes texte3 et texte4 sont en fait texte1 et texte2 à l'envers.

Maintenant, nous allons adapter la définition de la ligne racine. Changez-le de :

root = GridLayout(orientation='vertical', spacing=10, cols=1,rows=3)

à :

root = GridLayout(orientation='vertical', spacing=6, cols=1, rows=4, row_default_height=40)

Nous avons changé l'espacement de 10 à 6 et réglé la hauteur de ligne par défaut à 40 pixels. Changez le texte de l'étiquette (ligne suivante) en « text='Transposer Ver 0.8.0' ». Pour le reste, rien n'a changé sur cette ligne.

Now change the button definition line from… btn1 = Button(text = “ ” + text1,size=(680,40), size_hint=(None,None), halign='left', font_name='data/fonts/DroidSansMono.ttf', padding=(20,20)) to: btn1 = Button(text = “ ” + self.text1,size=(780,20), size_hint=(None, None), halign='left', font_name='data/fonts/DroidSansMono.ttf', padding=(20,2), background_color=[0.39,0.07,.92,1])

Maintenant changez la définition du bouton de :

btn1 = Button(text = "  " + text1,size=(680,40),
size_hint=(None,None),
halign='left',
font_name='data/fonts/DroidSansMono.ttf',
padding=(20,20))

à :

btn1 = Button(text = "    " + self.text1,size=(780,20),
size_hint=(None, None),
halign='left',
font_name='data/fonts/DroidSansMono.ttf',
padding=(20,2),
background_color=[0.39,0.07,.92,1])

Notice that I’ve changed the formatting of the first definition for clarity. The big changes are the size change from 680,40 to 780,20 and the background color for the button. Remember, we can change the background color for buttons, not “standard” labels. Next, we will define three AnchorLayout widgets for the three buttons that we will add in later. I named them al0 (AnchorLayout0), al1 and al2. We also add the code for the About Popup, and define our buttons along with the bind statements. This is shown on the next page, top left. Find the “s = GridLayout” line and change the spacing from 10 to 4. Next, add the following line after the s.bind line (right before the for loop): LoadLabels(0) This calls the LoadLabels routine with our default “which” of 0.

Remarquez que j'ai changé le format de la première définition pour plus de clarté. Les gros changements sont la taille qui passe de 680,40 à 780,20 et la couleur de fond du bouton. Rappelez-vous, on peut changer la couleur de fond pour les boutons, mais pas pour les étiquettes « standards ».

Ensuite, nous allons définir trois widgets AnchorLayout pour les trois boutons que nous ajouterons plus tard. Je les ai nommés al0 (AnchorLayout0), al1 et al2. Nous ajoutons également le code pour le Popup « à propos » et définissons nos boutons avec les paramètres de liaison (bind). Ceci est illustré à la page suivante, en haut à gauche.

Trouvez la ligne « s = GridLayout » et modifiez l'espacement de 10 à 4. Ensuite, ajoutez la ligne suivante après la ligne s.bind (juste avant la boucle for) :

ChargeEtiquettes(0)

Ceci appelle la routine ChargeEtiquettes avec notre « quelsens » par défaut qui vaut 0.

Next, comment out the entire for loop code. This starts with “for i in range(0,19):” and ends with “s.add_widget(btn)”. We don’t need this since the LoadLabels routine does this for us. Now, save your code and try to run it. You should see a deep purple button at the top, and our pretty blue BoundLabels. Plus, you will notice that the BoundLabels in the scroll window are closer together, which makes it much easier to read. We are almost through with our code, but we still have a few things to do. After the “sv = ScrollView” line add the following line… sv.size = (720, 320)

Ensuite, commentez la totalité du code de la boucle for. Cela commence par « for i in range(0,19): » et se termine par « s.add_widget(btn) ». Nous n'avons pas besoin de cette routine puisque ChargeEtiquettes le fait pour nous.

Maintenant, enregistrez votre code et essayez de l'exécuter. Vous devriez voir un bouton violet foncé en haut et nos BoundLabels d'un joli bleu. De plus, vous remarquerez que les BoundLabels dans la fenêtre de défilement sont plus rapprochés, ce qui en facilite grandement la lecture.

Nous sommes presque au bout de notre code, mais il nous reste quelques petites choses à faire. Après la ligne « sv = ScrollView », ajoutez la ligne suivante :

sv.size = (720, 320)

This sets the size of the ScrollView widget to 720 by 320 – which makes it wider within the root window. Now, before the “return root” line, add the code shown top right. Here we add the three buttons to the AnchorLayout widgets, create a GridLayout to hold the AnchorLayouts, and then finally add the AnchorLayouts to the GridLayout. Go back just below the “def Swap” routine and add the following… def ShowAbout(instance): popup.open() That’s it. Save and run the code. If you click on the About button, you will see the simple popup. Just click anywhere outside of the popup to make it go away.

Cela définit la taille du widget ScrollView à 720 sur 320, ce qui le rend plus large à l'intérieur de la fenêtre racine. Maintenant, avant la ligne « return racine », ajoutez le code que vous voyez en haut à droite.

Ici nous ajoutons les trois boutons aux widgets AnchorLayout, créons un GridLayout pour contenir les AnchorLayouts et enfin ajoutons les AnchorLayouts au GridLayout.

Retournez juste en dessous de la routine « def Echange » et ajoutez ce qui suit :

def AfficheAPropos(instance):

   popup.open()

C'est tout. Enregistrez et exécutez le code. Si vous cliquez sur le bouton « À propos », vous verrez le popup tout simple. Cliquez n'importe où en dehors du popup pour le faire disparaître.

Now our code is written. You can find the full code at http://pastebin.com/GftmjENs Next, we need to create our android package… but that will have to wait for next time. If you want to get set up and try packaging for Android before next month, you should go to http://kivy.org/docs/guide/packaging-android.html for the documentation on this. Be sure to follow the documentation carefully. See you next month.

Maintenant, notre code est écrit. Vous pouvez trouver le code complet ici : http://pastebin.com/T0kJ0q5z

Ensuite, nous devons créer notre paquet android… mais cela devra attendre la prochaine fois.

Si vous voulez vous préparer et essayer d'empaqueter pour Android avant le mois prochain, allez sur http://kivy.org/docs/guide/packaging-android.html pour trouver la documentation à ce sujet. Assurez-vous de suivre attentivement la documentation.

Rendez-vous le mois prochain.

issue65/python.txt · Dernière modification : 2012/10/21 15:29 de andre_domenech