program in python

22
THE INDEPENDENT MAGAZINE FOR THE UBUNTU LINUX COMMUNITY PROGRAMMING SERIES SPECIAL EDITION PROGRAM PROGRAM IN PYTHON IN PYTHON Volume Volume Six Six Parts 3 Parts 3 2-3 2-38 Full Circle Full Circle Magazine is neither affiliated, with nor endorsed by, Canonical Ltd.

Upload: hadieu

Post on 10-Feb-2017

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: PROGRAM IN PYTHON

THE INDEPENDENT MAGAZINE FOR THE UBUNTU LINUX COMMUNITY

PROGRAMMING SERIES SPECIAL EDITION

PROGRAMPROGRAM IN PYTHONIN PYTHON Volume Volume SixSix Parts 3Parts 32-32-388

Full Circle

Full Circle Magazine is neither affiliated, with nor endorsed by, Canonical Ltd.

Page 2: PROGRAM IN PYTHON

Full Circle Magazine Specials

full circle magazine

The articles contained in this magazine are released under the Creative Commons Attribution-Share Alike 3.0Unported license. This means you can adapt, copy, distribute and transmit the articles but only under the following conditions:

You must attribute the work to the original author in some way (at least a name, email or URL) and to this magazine by name ('full circle magazine') and the URL www.fullcirclemagazine.org (but not attribute the article(s) in any way that suggests that they endorse you or your use of the work). If you alter, transform, or build upon this work, you must distribute the resulting work under the same, similar or a compatible license.Full Circle Magazine is entirely independent of Canonical, the sponsor of Ubuntu projects and the views and opinions in the magazine should in no way be assumed to have Canonical endorsement.

Please note: this Special Edition is provided with absolutely no warranty whatsoever; neither the contributors nor Full Circle Magazine accept any responsibility or liability for loss or damage resulting from readers choosing to apply this content to theirs or others computers and equipment.

About Full Circle

Full Circle is a free, independent, magazine dedicated to the Ubuntu family of Linux operating systems. Each month, it contains helpful how-to articles and reader- submitted stories.

Full Circle also features a companion podcast, the Full Circle Podcast which covers the magazine, along with other news of interest.

Welcome to another 'single-topic special'In response to reader requests, we are assembling the content of some of our serialised articles into dedicated editions.

For now, this is a straight reprint of the series 'Programming in Python', Parts 27-31 from issues #60 through #67, allowing peerless Python professor Gregg Walters #66 as time off for good behaviour.

Please bear in mind the original publication date; current versions of hardware and software may differ from those illustrated, so check your hardware and software versions before attempting to emulate the tutorials in these special editions. You may have later versions of software installed or available in your distributions' repositories.

Enjoy!

Find Us

Website: http://www.fullcirclemagazine.org/

Forums: http://ubuntuforums.org/forumdisplay.php?f=270

IRC: #fullcirclemagazine on chat.freenode.net

Editorial Team

Editor: Ronnie Tucker (aka: RonnieTucker) [email protected]

Webmaster: Rob Kerfia (aka: admin / linuxgeekery- [email protected]

Editing & ProofreadingMike Kennedy, Lucas Westermann,Gord Campbell, Robert Orsino,Josh Hertel, Bert Jerred

Our thanks go to Canonical and the many translation teams around the world.

Page 3: PROGRAM IN PYTHON

full circle magazine #60 6 �������� �

HHOOWW--TTOOWritten by Greg D. Walters BBeeggiinnnniinngg PPyytthhoonn -- PPaarrtt 3322

I must say, I love my Androidtablet. While I use it every day,it's not yet a replacement formy desktop. And I must also

admit, most of what I use it for ispretty much what everyone usestheirs for: web browsing, listeningto music, watching videos, playinggames, and so on. I try to justify itby having apps that deal withgrocery and todo lists, findingcheap gas, fun things for ourgrandson, etc. It's really a toy forme right now. Why use a fancytouch-screen tablet to do yourgrocery list? Let's face it... it's thecool looks of envy that people giveme in the store when they see merolling the cart down the aisle and Itap my tablet to mark items off thelist. Ahh--- the geek factor RULES!Of course, I can use the back of anold envelope to hold my list. Butthat wouldn't be cool and geeky,now, would it?

Like 99% of geeky married menin the world, I am married to a non-geek woman. A wonderful lovingwoman, to be sure, but a non-geekwho, when I start drooling at thelatest gadget, sighs, and says

something like “Well, if you REALLYthink we need that...”. Then shegives me the same look I give heras she is lovingly fondles the 50thpair of shoes at the store.

In all honesty, it wasn't hard toget the first tablet into our house. Ibought it for my wife while she wasgoing through chemotherapy. Shetried to use a laptop for a while,but the heat and weight onher lap was too muchafter a while. E-bookson a laptop for herwasn't an option,so when she triedto read, she hadto juggle thebook, and thelaptop, and themp3 player. Allwhile being tiedto a recliner withtubes running intoher arm filling herwith nasty chemicals.When I got her thetablet, it was the best of allworlds. She could read an e-book,listen to music, watch a TV show,browse the web, check her E-mail,update her cancer blog, follow her

friends on facebook, and playgames - all on a device that waslight and cool. If she got tired, shecould just slip it off to the sidebetween her and the recliner (orbed when she was home trying toregain strength). MUCH better thana bulky laptop, and book, mp3player, remote control, and more.

As she was gettingpumped full of noxious

chemicals, I wouldcommandeer atable and chair inthe corner of thetreatmentroom, near apower outlet,and try to workon my six-yearold laptop. Inbetween

projects, I woulddo research on

Androidprogramming. I found

out that most programmingfor Android is done in Java. I hadalmost resigned myself to re-learning Java when I stumbledacross a few tools that allow

Python programming for theAndroid Operating system. One ofthese tools is called “SL4A”. SL4Astands for Scripting Layer forAndroid. That's what we willconcentrate on in the next coupleof articles. We'll really focus ongetting SL4A set up on Android inthis one.

You might ask, why in the worldI would be talking about Androidprogramming in a magazinedesigned for Linux. Well, thesimple reason is that the core ofAndroid is Linux. Everything thatAndroid is, sits on top of Linux!

Many web pages show how toload SL4A into the AndroidEmulator for Desktops. We'll lookat doing that another time, but fornow we'll deal with the Androiddevice itself. To install SL4A onyour Android device, go tohttp://code.google.com/p/android-scripting/; you'll find theinstallation file for SL4A. Don't beabsolutely confused here. There's asquare High Density barcode thatyou tap to download the APK. Besure that you have the “Unknown

Page 4: PROGRAM IN PYTHON

full circle magazine #60 7 �������� �

HOWTO - BEGINNING PYTHON 32Sources” option enabled in theApplication settings. It's a quickdownload. Once you have itdownloaded and installed, goahead and find the icon, and tap it.What you will see is a ratherdisappointing black screen saying“Scripts...No matches found”.That's OK. Hit the menu button andselect View. You'll see a menu.Select Interpreters. Then selectmenu again, and select Add. Fromthe next menu, select Python 2.6.2.This should ask you to start abrowser session to downloadPython for Android. Once this isinstalled, select Open. You'll get ascreen menu with the options toInstall, Import Modules, BrowseModules, and Uninstall modules.Select Install. Now Python willdownload and install along withother extra modules. In addition,you'll get some sample scripts.Finally, tap the back button andyou'll see Python 2.6.2 installed inthe interpreters screen. Tap againon the back button and you'll see alist of some sample python scripts.

That's all we are going to do thistime. All I wanted to do is whetyour appetite. Explore Python onAndroid. You might also want tovisit

http://developer.android.com/sdk/index.html to get the Android SDK(Software Development Kit) foryour desktop. It includes anAndroid Emulator so you can playalong. Setting up the SDK is reallypretty easy on Linux, so youshouldn't have too much trouble.

������ ��� � ������������������� ����������� ����� ���������

Greg is the owner of RainyDaySolutions, LLC, a consulting companyin Aurora, Colorado, and has beenprogramming since 1972. He enjoyscooking, hiking, music, and spendingtime with his family. His website iswww.thedesignatedgeek.net.

How to Include Accents from the Keyboardby Barry Smith

I f your Linux system is in French, German, or Spanish, and,therefore, requiring accents, or if, occasionally, you need to useaccents which do not appear in English words, many users do notknow that there is a very easy way to do this from the keyboard.

The following applies to only the UK keyboard.

Acute accentPress Alt Gr + ; (semi-colon) Lift hand then press the desired vowel é

CircumflexPress Alt Gr + ' (apostrophe) Lift hand then press the desired vowel î

Grave accentPress Alt Gr + # (hache) Lift hand then press the desired vowel è

UmlautPress Alt Gr + [ Lift hand then press u ü

ñ - Press Alt Gr + ] Lift hand then press n ñ

œ - Press Shift + Alt Gr Lift hand then press o then press e œThe œ will not appear until after the e is keyed.

To get ¿ and ¡ (inverted exclamation mark) which I use all the time inSpanish before questions, and exclamations, press Alt Gr + Shift,keeping both keys pressed, then hit _ (underscore) for ¿ or hit !(exclamation mark) for ¡.

If you want any of these in capitals, just press Shift before keying inthe letter.

Page 5: PROGRAM IN PYTHON

full circle magazine #61 7�������� �

HHOOWW--TTOOWritten by Greg D. Walters BBeeggiinnnniinngg PPyytthhoonn -- PPaarrtt 3333

This time, we’ll set up theAndroid SDK on our Linuxdesktop. We’ll also createa virtual Android device,

install SL4A and python on it, anddo a quick test.

Please be aware, this is notsomething you would want to dofor machines that have less than 1GB of ram. The emulator eats up ahuge amount of memory. I’ve triedit on a laptop running Ubuntu withonly 512 MB of ram. It WILL work,but it is REALLY slow.

Here’s a quick list of what we’lldo. We’ll go step-by-step in aminute.• Install the Java JDK6.• Install the Android SDK starterpack.• Create and setup AVDs.• Test AVD, and install SL4A andPython.

In reality, we should also installEclipse and the Android ADT pluginfor Eclipse, but, since we won’t bedealing with Eclipse in this set ofarticles, we can bypass that. If youwant to include those steps, head

over tohttp://developer.android.com/sdk/installing.html to see all the stepsin the suggested order. Let’s getstarted.

STEP 1 - Java JDK 6

From everything I’ve read andtried, it must be the actual Sunrelease. OpenJDK is not supposedto work. You can find informationon this on the web, but here’s thesteps that I did. In a terminal, typethe following...

sudo add­apt­repositoryppa:ferramroberto/java

sudo apt­get update

sudo apt­get install sun­java6­jdk

Once everything here is done,you will want to edit your .bashrcfile to set “JAVA_HOME” soeverything runs correctly. I usedgedit and, at the bottom of thefile, I added the following line...

exportJAVA_HOME=”/usr/lib/jvm/java­6­sun­1.6.0.06”

Save the file and move on tostep 2.

STEP 2 - Android SDKStarter Pack

Now the actual “fun” begins.You’ll want to go todeveloper.android.com/sdk/index.html. This is where the SDK islocated. Download the latestversion for Linux, which, at thetime of this writing, is android-sdk_r18-linux.tgz. Using ArchiveManager, unpack it somewhereconvenient. I put it in my homedirectory. Everything runs directlyfrom this folder, so you really don’thave to install anything. So thepath for me is/home/greg/android-sdk-linux.Navigate to this folder, then go tothe tools folder. There you will finda file called “android”. This is whatruns the actual SDK. I created alauncher on my desktop to make iteasy to get to.

Now the boring part. Run theandroid file, and the Android SDKManager will start. It will go out

and update the platforms that areavailable. I will warn you now thatthis process will take some time, sodon’t bother if you don’t have a lotof time to deal with it. For the sakeof brevity, I would suggest you getonly one platform to start. A goodone to begin with is the Android2.1 platform, since, for the mostpart, if you develop for an olderplatform, there should be noproblem running on a newerplatform. You also need to get theTools set as well. Simply check thebox next to those two items, thenclick on the install button. Onceyou get the platform of yourchoice, and the tool set, you arealmost ready to create your firstvirtual machine.

STEP 3 - Create and setup your first AVD

Back in the Android SDKManager, select Tools from themain menu, then select ManageAVDs. This will open a new window.Since this is the first time, therewon’t be any virtual devices set up.Click on the “New” button. Thisopens yet another window where

Page 6: PROGRAM IN PYTHON

full circle magazine #61 8 �������� �

HOWTO - BEGINNING PYTHON 33we define the properties of thevirtual Android device. Here’s thesteps that you should use to set upa simple Android emulator device:• Set the name of the device. Thisis important if you have more thanone device.• Set the target platform level.• Set the size of the SD card (seebelow).• Set the skin resolution.• Create the device.

So, In the name text box, type“Test1”. Under the target combo-box, select Android 2.1 - API Level7. In the text box for “SD Card:”enter 512 and make sure thedropdown shows “MiB”. Under“Skin”, set the resolution to800x600. (You can play with theother built-in sizes on your own.)Finally, click the “Create AVD”button. Soon, you’ll see a messagebox saying that the AVD wascreated.

STEP 4 - Testing theAVD and installingSL4A and Python

Now, finally, we can have a bitof fun. Highlight the AVD you justcreated and click on the Start

button. In the dialog box that popsup, simply click the “Launch”button. Now, you have to wait afew minutes for the virtual deviceto be created in memory, and theAndroid platform to beloaded and started.(We’ll talk aboutspeeding thisprocess up inlater runs.)

Once theAVD starts upand you havethe “home”screen up, youwill install SL4A.Using thebrowser or thegoogle web searchbox on the home screen,search for “sl4a”. Go to thedownloads page, and you’lleventually find the web page forthe downloads athttp://code.google.com/p/android-scripting/downloads/list.

Scroll down the page until youget to the sl4a_r5 link. Open thelink and tap on the “sl4a_r5.apk”link. Notice I said “tap” rather than“click”. Start thinking about usingyour finger to tap the screen ratherthan clicking the mouse. It will

make your programming transitioneasier. You’ll see the downloadstart. You may have to pull downthe notification bar at the top toget to the downloaded file. Tap on

that, then tap the installbutton.

Once the file isdownloaded,you’ll bepresented withthe option toopen thedownloadedapp or to tap“Done” to exitthe installer.

Here we will wantto tap “Open”.

Now SL4A will start.You’ll probably see a dialog

asking if you will agree to usagetracking. Either accept or refusethis - it’s up to you. Before we goany farther, you should know somekeyboard shortcuts that will helpyou move around. Since we don’thave a “real” Android device,buttons like Back, Home, andMenu, aren’t available. You’ll needthem to navigate around. Here’s afew important shortcuts.

Back - Escape

Home - HomeMenu - F2

Now we will want to downloadand install python into SL4A. To dothis, first tap Menu (press F2).Select “View” from the menu. Nowselect “Interpreters”. It looks likenothing happened, but tap Menuagain (F2), then select “Add” fromthe popup. Now scroll down andselect “Python 2.6.2”. This willdownload the base package forPython for Android. Install thepackage, then open it. You will bepresented with four options.Install, Import Modules, BrowseModules, and Uninstall Module.Tap on Install. This will startdownloading and installing all thepieces of the latest Python forAndroid. This can take a fewminutes.

Once everything is done, tapBack (escape key) until you get tothe SL4A Interpreters screen. Noweverything is loaded for us to playin Python on Android. Tap Python2.6.2, and you’ll be in the“standard” Python shell. This is justlike the shell on your desktop. Typethe following three lines, one at atime, into the shell. Be sure to waitfor the “>>>” prompt each time.

Page 7: PROGRAM IN PYTHON

full circle magazine #61 9 �������� �

Greg is the owner of RainyDaySolutions, LLC, a consulting companyin Aurora, Colorado, and has beenprogramming since 1972. He enjoyscooking, hiking, music, and spendingtime with his family. His website iswww.thedesignatedgeek.net.

HOWTO - BEGINNING PYTHON 33import android

droid = android.Android()

droid.makeToast(“Hello fromPython on Android”)

After you type the last line andpress Enter, you’ll see a roundedcorner box at the center bottom ofthe shell that says “Hello fromPython on Android”. That’s whatthe “droid.makeToast” commanddoes.

You’ve written your first Pythonscript for Android. Neat, huh?

Now let’s create a shortcut onthe Android home screen. Tap theHome key (Home button). If youchose the 2.1 platform, you shouldsee a slider bar on the far right ofthe screen. If you chose anotherplatform, it might be a square orrectangle consisting of smallsquares. Either way, this gets youto the Apps screen. Tap that, andfind the SL4A icon. Now perform a“long tap” (long click), which willcreate a shortcut on the Homescreen. Move the shortcutwherever you want it.

Next, we will create our firstsaved script. Go back into SL4A.

You should be presented with thesample scripts that come withPython 4 Android. Tap the Menubutton and select “Add”. Select“Python 2.6.2” from the list. You’llbe presented with the script editor.At the top is the filename box with“.py” already filled out. Below thatis the editor window that alreadyhas the first two lines of ourprogram entered for us. (I includedthem below in italics so you cancheck it. We also used these twolines in our first sample.)

import android

droid = android.Android()

Now, enter the following twolines to the python script.

uname =droid.dialogGetInput(“What’syour name?”)

droid.makeToast(“Hello %sfrom Python on Android”) %uname.result

The first new line will create adialog box (droid.dialogGetInput())that asks for the user’s name. Theresponse is returned to ourprogram in uname.result. We’vealready used the droid.makeToast()function.

Name the file andtest1.py, thentap Done, and tap “Save & Run”. Ifeverything worked, you should seea dialog box asking for your name.After you enter it, you should seethe alert at the bottom of thescreen saying “Hello Your Namefrom Python on Android”.

That’s all for this time. For now,there’s a TON of documentationabout SL4A for free on the web.You can play a bit on your own untilnext time. I’d suggest that youstart by going tohttp://code.google.com/p/android-scripting/wiki/Tutorials.

O'Reilly are looking forward tocelebrating Velocity's 5th Year with youJune 25-27, at the Santa ClaraConvention Center. You'll meet thesmartest people working in webperformance and operations at theO'Reilly Velocity Conference. Web andmobile users expect betterperformance than ever before. Tomeet, and exceed, their expectations,you need to master a daunting array ofweb performance, operations, andmobile performance issues. Velocityoffers the best opportunity to learn thenewest info on what you need to knowto build a faster and stronger web.

Take advantage of this rare opportunityto meet face-to-face with a cadre ofindustry leaders who are taking webperformance and operations to thenext level. Velocity packs a wealth ofbig ideas, know-how, and connectionsinto three concentrated days. You'll beable to apply what you've learnedimmediately and you'll be wellprepared for what lies ahead with fourin-depth tracks covering the keyaspects of web performance,operations, mobile performance, andVelocity culture.

Velocity has sold out the last two years,so if you want to reserve your spot atVelocity 2012, register now and save anadditional 20% with code FULLCIR.

Page 8: PROGRAM IN PYTHON

full circle magazine #62 8 �������� �

HHOOWW--TTOOWritten by Greg D. Walters BBeeggiinnnniinngg PPyytthhoonn -- PPaarrtt 3344

This time, we’ll finish upusing SL4A. We’ll make alarger program and thensend it to the virtual

machine via ADB.

Let’s deal with our code first. Inthis, we’ll simply be trying outsome of the “widgets” that areavailable to us when using SL4A.Start on your desktop using yourfavorite editor.

Enter the code shown top rightand save it (but don’t try to run it)as “atest.py”.

The first line imports theandroid library. We create aninstance of it in the second line.Line 3 creates and displays a dialogbox with the title “Hello”, theprompt of “What’s your name?”, atext box for the user to enter theirname, and two buttons, “OK” and“Cancel”. Once the user presses“OK”, the response is returned inthe variable uname. The last line(so far) then says “Hello{username} from python onAndroid!”. This isn’t new, we didthis before. Now we’ll add more

code (above).

Save your code as atest1.py.We’ll be sending this to our virtualmachine after we discuss what itdoes.

Take a look at the first four lineswe just entered. We create an alerttype dialog asking “Would you liketo play a game?”. In the case of analert type dialog, there’s no textbox to enter anything. The nexttwo lines say to create two

buttons, one with the text “Yes”,which is a “positive” button, andone with the text “No”, a“negative” button. The positiveand negative buttons refer to theresponse returned - either“positive” or “negative”. The nextline then shows the dialog. Thenext seven lines wait for aresponse from the user.

We create a simple loop (whileTrue:) then wait for a response forup to 10 seconds by using the

droid.eventWait(value) call. Theresponse (either “positive” or“negative”) will be returned in -you guessed it - the responsevariable. If response has the nameof “dialog”, then we will break outof the loop and return theresponse. If nothing happensbefore the timeout occurs, wesimply break out of the loop. Theactual information returned in theresponse variable is something likethis (assuming the “positive” or“Yes” button is pressed)...

import android

droid = android.Android()uname = droid.dialogGetInput("Hello","What's your name?")droid.makeToast("Hello %s from python on Android!" % uname.result)

droid.dialogCreateAlert(uname.result,"Would you like to play a game?")droid.dialogSetPositiveButtonText('Yes')droid.dialogSetNegativeButtonText('No')droid.dialogShow()while True: #wait for events for up to 10 seconds...

response = droid.eventWait(10000).resultif response == None:breakif response["name"] == "dialog":break

droid.dialogDismiss()

Page 9: PROGRAM IN PYTHON

full circle magazine #62 9 �������� �

HOWTO - BEGINNING PYTHON 34

{u’data’: {u’which’:u’positive’}, u’name’:u’dialog’, u’time’:1339021661398000.0}

You can see that the value ispassed in the ‘data’ dictionary, thedialog key is in the ‘name’dictionary, and there is a ‘time’value that we don’t care abouthere.

Finally we dismiss the dialogbox.

Before we can send our code tothe virtual machine, we have tostart the virtual machine. Startyour Android emulator. Once itstarts up, notice that the title barhas four digits at the start of thetitle. This is the port that themachine is listening on. In my case(and probably yours) it’s 5554.

Now, let’s push it to our virtualmachine. Open a terminal windowand change to the folder you savedthe code in. Assuming you have setyour path to include the SDK, type

adb devices

This asks adb to show anydevices that are connected. Thiscan include not only the Android

emulator but also anysmartphones, tablets, or otherAndroid devices. You should seesomething like this...

List of devices attachedemulator­5554 device

Now that we are sure that ourdevice is attached, we want topush the application to the device.The syntax is...

adb push source_filenamedestination_path_and_filename

So, in my case it would be...

adb push atest1.py/sdcard/sl4a/scripts/atest1.py

If everything works correctly,you’ll get a rather disappointingmessage similar to this...

11 KB/s (570 bytes in 0.046s)

Now, onthe Androidemulator,start SL4A.You shouldsee all of thepythonscripts, and,in there you

should see atest1.py. Tap(click) on ‘atest1.py’, andyou’ll see a popup dialog with6 icons. From left to right,they are “Run in a dialogwindow”, “Run outside of awindow”, “Edit”, “Save”,“Delete”, and “Open in an externaleditor”. Right now, tap (click) onthe far left icon “Run in a dialogwindow” so you can see whathappens.

You’ll see the first dialog askingfor your name. Enter something inthe box and tap (click) the ‘Ok’button. You’ll see the hellomessage. Next, you’ll see the alertdialog. Tap (click) on either buttonto dismiss the dialog. We aren’tlooking at the responses yet so itdoesn’t matter which one youchoose. Now we’ll add some morecode (top right).

I’m sure you can figure out that

this set of code simply checks theresponse, and, if it’s ‘None’ due toa timeout, we simply print “Timedout.” And, if it’s actually somethingwe want, then we assign the datato the variable rdialog. Now addthe next bit of code (below)...

This part of the code will look atthe data passed back by thebutton-press event. We check tosee if the response has a “which”key, and, if so, it’s a legitimatebutton press for us. We then checkto see if the result is a “positive”(‘Ok’ button) response. If so, we’llcreate another alert dialog, butthis time, we will add a list of itemsfor the user to choose from. In thiscase, we offer the user to select

if response==None:print "Timed out."

else:rdialog=response["data"]

if rdialog.has_key("which"):result=rdialog["which"]if result=="positive":

droid.dialogCreateAlert("Play a Game","Select a game to play")droid.dialogSetItems(['Checkers','Chess','Hangman','Thermal

Nuclear War']) # 0,1,2,3droid.dialogShow()resp = droid.dialogGetResponse()

Page 10: PROGRAM IN PYTHON

full circle magazine #62 10�������� �

Greg is the owner of RainyDaySolutions, LLC, a consulting companyin Aurora, Colorado, and has beenprogramming since 1972. He enjoyscooking, hiking, music, and spendingtime with his family. His website iswww.thedesignatedgeek.net.

HOWTO - BEGINNING PYTHON 34from a list including Checkers,Chess, Hangman, and ThermalNuclear War, and we assign thevalues 0 to 3 to each item. (Is thisstarting to seem familiar? Yes, it’sfrom a movie.) We then display thedialog and wait for a response. Thepart of the response we areinterested in is in the form of adictionary. Assuming the usertapped (clicked) on Chess, theresulting response comes back likethis...

Result(id=12,result={u’item’:1},error=None)

In this case, we are reallyinterested in the result portion of

the returned data. The selection is#1 and is held in the ‘item’ key.Here’s the next part of the code(above right)...

Here we check to see if theresponse has the key “item”, and, ifso, assign it to the variable “sel”.Now we use an if/elif/else loop tocheck the values and deal withwhichever is selected. We use thedroid.makeToast function todisplay our response. Of course,you could add your own code here.Now for the last of the code(bottom right)...

As you can see, we simplyrespond to the other types ofbutton-presses here.

Save, push, and run theprogram.

As you can see, SL4A gives you

the ability to make “GUIfied”applications, but not full gui apps.This however, should not keep youfrom going forward and starting towrite your own programs forAndroid. Don’t expect to put theseup on the “market”. Most peoplereally want full GUI type apps. We’lllook at that next time. For moreinformation on using SL4A, simplydo a web search and you’ll find lotsof tutorials and more information.

By the way, you can pushdirectly to your smartphone ortablet in the same way.

As usual, the code has been putup on pastebin athttp://pastebin.com/REkFYcSU

See you next time.

if resp.result.has_key("item"):sel = resp.result['item']if sel == 0:

droid.makeToast("Enjoy your checkers game")elif sel == 1:

droid.makeToast("I like Chess")elif sel == 2:

droid.makeToast("Want to 'hang around' for a while?")else:

droid.makeToast("The only way to win is not to play...")

elif result=="negative":droid.makeToast("Sorry. See you later.")

elif rdialog.has_key("canceled"):print "Sorry you can't make up your mind."

else:print "unknown response=",response

print "Done"

Page 11: PROGRAM IN PYTHON

full circle magazine #63 7�������� �

HHOOWW--TTOOWritten by Greg D. Walters BBeeggiinnnniinngg PPyytthhoonn -- PPaarrtt 3355

This time, we are going totake a short detour fromour exploration ofAndroid programming,

and look at a new framework forGUI programming called Kivy.You’ll want to head over tohttp://kivy.org and download andinstall the package – beforegetting too far into this month’sinstallment. The Ubuntuinstallation instructions can befound athttp://kivy.org/docs/installation/installation-ubuntu.html.

First off, Kivy is an open sourcelibrary that makes use of multi-touch displays. If that isn’t coolenough, it’s also cross-platform,which means that it will run onLinux, Windows, Mac OSX, IOS andAndroid. Now you can see why weare talking about this. Butremember, for the most part,anything you code using Kivy, canrun on any of the above platformswithout recoding.

Before we go too far, let memake a couple of statements. Kivyis VERY powerful. Kivy gives you a

new set of tools to make your GUIprogramming. All that having beensaid, Kivy is also fairly complicatedto deal with. You are limited to thewidgets that they have provided. Inaddition, there is no GUI designerfor Kivy, so you have to do a GREATdeal of pre-planning before you tryto do anything complicated. Alsoremember, Kivy is continuallyunder development so things canchange quickly. So far, I haven’tfound any of my test code that hasbroken by a new version of Kivy,but that’s always a possibility.

Rather than jump in and createour own code this month, we’lllook at some of the examples that

come with Kivy, and, next month,we’ll “roll our own”.

Once you’ve unpacked Kivy intoits own folder, use a terminal andchange to that folder. Mine is in/home/greg/Kivy-1.3.0. Nowchange to the examples folder,then to the widgets folder. Let’slook at the accordion_1.pyexample.

It’s very simple, but shows areally neat widget. Below is theircode.

As you can see, the first threelines are import statements. Anywidget you use must be imported,

and you must always import Appfrom kivy.app.

The next eight lines are themain application class. The class isdefined, then a routine called buildis created. You will almost alwayshave a build routine somewhere inyour Kivy programs. Next we set aroot object from the Accordionwidget. Next we create fiveAccordionItems and set their title.We then add ten labels with thetext “Very big content”. We thenadd each label to the root widget(the Accordion) and then finally wereturn the root object. This, inessence, displays the root object inthe window that Kivy creates for

from kivy.uix.accordion import Accordion, AccordionItemfrom kivy.uix.label import Labelfrom kivy.app import App

class AccordionApp(App):def build(self):

root = Accordion()for x in xrange(5):

item = AccordionItem(title='Title %d' % x)item.add_widget(Label(text='Very big content\n' * 10))root.add_widget(item)

return root

if __name__ == '__main__':AccordionApp().run()

Page 12: PROGRAM IN PYTHON

full circle magazine #63 8 �������� �

HOWTO - BEGINNING PYTHON 35us. Finally we have the “if__name__” statement and then runthe application.

Go ahead and run it to see whatit does.

You will see that in a momentor two, a window opens up withfive vertical bars in it. Clicking on abar causes it to open up revealingthe ten labels. Of course, each barhas the same text in the ten labels,but you can figure out how to fixthat.

The Accordion widget can beused for any number of things, butthe thing that has always jumpedto my mind is for a configurationscreen... each bar being a differentconfiguration set.

Next we’ll look at thetextalign.py example. It’s not as“sexy” as the last one, but it’s agood example that gives you someimportant information for later on.

Before we look at the code, runthe program.

What you should see is a labelat the top of the window, a set ofnine red boxes with text in a 3x3

grid, and four buttons along thebottom of the window. As you click(tap) each of the buttons, thealignment of the text within thered boxes will change. The mainreason you would want to payattention to this example is how touse and control some of theimportant widgets as well as howto change the alignment in yourwidgets, which is not completelyintuitive.

Above right is their code for thisone. I’ll break it into pieces. Firstthe import code (above right).

Below is something special.They created a class with no codein it. I’ll discuss that in a fewminutes:

class BoundedLabel(Label):

pass

Next a class called “Selector”(below) is created:

class Selector(FloatLayout):

app = ObjectProperty(None)

Now the Application class iscreated.

Here the routine select iscreated. A GridLayout widget iscreated (called grid) which has 3rows and 3 columns. This grid isgoing to hold the nine red boxes.

for valign in ('bottom','middle', 'top'):

for halign in ('left','center', 'right'):

Here we have two loops, oneinner and one outer.

label = BoundedLabel(text='V:%s\nH: %s' % (valign,

halign),

size_hint=(None, None),

halign=halign, valign=valign)

In the code above, an instanceof the BoundedLabel widget iscreated, once for each of the ninered boxes. You might want to stophere and say “But wait! There isn’ta BoundedLabel widget. It just hasa pass statement in it.” Well, yes,and no. We are creating aninstance of a custom widget. As Isaid a little bit above, we’ll talkmore about that in a minute.

In the code block (top right,next page), we examine thevariable ‘case’ which is passed intothe select routine.

from kivy.app import Appfrom kivy.uix.label import Labelfrom kivy.uix.gridlayout import GridLayoutfrom kivy.uix.floatlayout import FloatLayoutfrom kivy.properties import ObjectProperty

class TextAlignApp(App):

def select(self, case):

grid = GridLayout(rows=3, cols=3, spacing=10, size_hint=(None, None),pos_hint={'center_x': .5, 'center_y': .5})

Page 13: PROGRAM IN PYTHON

full circle magazine #63 9 �������� �

HOWTO - BEGINNING PYTHON 35Here, the grid is removed, to

clear the screen.

if self.grid:

self.root.remove_widget(self.grid)

The bind method here sets thesize, and the grid is added to theroot object.

grid.bind(minimum_size=grid.setter('size'))

self.grid = grid

self.root.add_widget(grid)

Remember in the last example Isaid that you will almost alwaysuse a build routine. Here is the onefor this example. The root object iscreated with a FloatLayout widget.Next (middle right) we call theSelector class to create a Selectorobject, then it’s added to the rootobject, and we initialize the displayby calling self.select(0).

Finally the application isallowed to run.

TextAlignApp().run()

Now, before we can go anyfurther, we need to clear up a fewthings. First, if you look in the

folder that holds the .py file, you’llnotice another file calledtextalign.kv. This is a special filethat Kivy uses to allow you tocreate your own widgets and rules.When your Kivy application starts,it looks in the same directory forthe .kv helper file. If it is there,then it loads it first. Here’s thecode in the .kv file.

This first line tells Kivy whatminimum version of Kivy that mustbe used to run this app.

#:kivy 1.0

Here the BoundedLabel widgetis created. Each of the red boxes inthe application is a BoundedLabel.

Color sets the background colorof the box to red (rgb: 1,0,0). TheRectangle widget creates a (youguessed it) rectangle. When we callthe BoundedLabel widget in theactual application code, we arepassing a label as the parent. Thesize and position (here in the .kvfile) are set to whatever the sizeand position of the label are.

Here (right, next page) theSelector widget is created. This isthe four buttons that appear at thebottom of the window as well as

the label across the top of thewindow.

Notice that the label that makesup the title at the top of thewindow has a position (pos_hint)as top, has a height of 50 pixelsand a font size of 16. Each of thebuttons has an alignment for thetext of center. The on_releasestatement is a bind-like statementso that, when the button is

released, it calls (in this case)root.app.select with a case value.

Hopefully, this is beginning tomake sense now. You can see whyKivy is so powerful.

Let’s talk for a moment abouttwo widgets that I have passedover in the discussion of theapplication code, The GridLayoutand the FloatLayout.

if case == 0:label.text_size = (None, None)

elif case == 1:label.text_size = (label.width, None)

elif case == 2:label.text_size = (None, label.height)else:label.text_size = label.size

grid.add_widget(label)

def build(self):self.root = FloatLayout()

self.selector = Selector(app=self)self.root.add_widget(self.selector)self.grid = None

self.select(0)return self.root

<BoundedLabel>:canvas.before:

Color:rgb: 1, 0, 0

Rectangle:pos: self.pos

size: self.size

Page 14: PROGRAM IN PYTHON

full circle magazine #63 10�������� �

Greg is the owner of RainyDaySolutions, LLC, a consulting companyin Aurora, Colorado, and has beenprogramming since 1972. He enjoyscooking, hiking, music, and spendingtime with his family. His website iswww.thedesignatedgeek.net.

HOWTO - BEGINNING PYTHON 35

The GridLayout is a parentwidget that uses a row and columndescription to allow widgets to beplaced in each cell. In this case, it isa 3x3 grid (like a Tic-Tac-Toe (orNaughts and Crosses) board).

__|__|____|__|__| |

When you want to place awidget into a GridLayout, you usethe add_widget method. Here liesa problem. You can’t specify whichcontrol goes into which grid cellother than the order in which youadd them. In addition, each widgetis added from left to right, top tobottom. You can’t have an emptycell. Of course, you can cheat. I’llleave that up to you to figure out.

The FloatLayout widget seemsto be just a parent container forother child widgets.

I’ve glossed over a few pointsfor now. My intent this time wassimply to get you somewhatexcited about the possibilities thatKivy has to offer. In the nextcouple of articles, we’ll continue toexplore what Kivy has for us, howto use various widgets, and how tocreate an APK to publish our

applications to Android.

Until then, exploremore of the examples inKivy, and be sure to go tothe documentation pagefor Kivy athttp://kivy.org/docs/.

<Selector>:Label:pos_hint: {'top': 1}

size_hint_y: Noneheight: 50

font_size: 16text: 'Demonstration of text valign and halign'BoxLayout:

size_hint_y: Noneheight: 50

ToggleButton:halign: 'center'

group: 'case'text: 'label.text_size =\n(None, None)'on_release: root.app.select(0)state: 'down'

ToggleButton:halign: 'center'

group: 'case'text: 'label.text_size =\n(label.width, None)'on_release: root.app.select(1)

ToggleButton:halign: 'center'group: 'case'

text: 'label.text_size =\n(None, label.height)'on_release: root.app.select(2)

ToggleButton:halign: 'center'group: 'case'

text: 'label.text_size =\n(label.width, label.height)'on_release: root.app.select(3)

Page 15: PROGRAM IN PYTHON

full circle magazine #64 7�������� �

HHOOWW--TTOOWritten by Greg D. Walters BBeeggiinnnniinngg PPyytthhoonn -- PPaarrtt 3366

Before I begin, I want tonote that this articlemarks three years of theBeginning Programming

using Python series. I want tothank Ronnie and the entire staffof Full Circle Magazine for all theirsupport and especially, you, thereaders. I NEVER thought that thiswould continue this long.

I also want to take a second tonote that there has been somecomments floating around theether that, after three years, theword “Beginning” might bemisplaced in the title of this series.After all, after three years, wouldyou still be a beginner? Well, onsome levels, I agree. However, Istill get comments from readerssaying that they just found theseries and Full Circle Magazine,and that they are now runningback to the beginning of the series.So, those people ARE beginners.So, as of part 37, we’ll drop“Beginning” from the series title.

Now to the actual meat of thisarticle... more on Kivy.

Imagine you play guitar. Not airguitar, but an actual guitar.However, you aren’t the best guitarplayer, and some chords areproblematical for you. Forexample, you know the standard C,E, G, F type chords, but somechords – like F# minor or C# minor– while doable, are hard to get yourfingers set in a fast song. What doyou do, especially if the gig is onlya couple of weeks away and youHAVE to be up to speed TODAY?The workaround for this is to usethe Capo (that funny clippy thingthat you see sometimes on theneck of the guitar). This raises thekey of the guitar and you usedifferent chords to match the restof the band. This is calledtransposing. Sometimes, you cantranspose on the fly in your head.Sometimes, it’s easier to sit downon paper and work out that if, for

example, the chord is F# minor andyou put the capo on fret 2, you cansimply play an E minor. But thattakes time. Let’s make an app thatallows you to simply scroll throughthe fret positions to find theeasiest chords to play.

Our app will be fairly simple. Atitle label, a button with our basicscale as the text, a scrollview (awonderful parent widget thatholds other controls and allowsyou to “fling” the inside of thecontrol to scroll) holding a numberof buttons that have repositionedscales as the text, and an exitbutton. It will look SOMETHINGlike the text below.

Start with a new python filenamed main.py. This will beimportant if/when you decide tocreate an Android app from Kivy.

Now we’ll addour importstatementswhich are shownon the next page, top right.

Notice the second line,“kivy.require(‘1.0.8’)”. This allowsyou to make sure that you can usethe latest and greatest goodiesthat Kivy provides. Also notice thatwe are including a system exit (line3). We’ll eventually include an exitbutton.

Here is the beginning of ourclass called “Transpose”.

class Transpose(App):

def exit(instance):

sys.exit()

Now we work on our build

­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­Transposer Ver 0.1

C C#/Db D D#/Eb E F F#/Gb G G#/Ab A A#/Bb B C____________________________________________________________________

1| C#/Db D D#/Eb E F F#/Gb G G#/Ab A A#/Bb B C C#/Db2| D D#/Eb E F F#/Gb G G#/Ab A A#/Bb B C C#/Db D­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

Page 16: PROGRAM IN PYTHON

full circle magazine #64 8 �������� �

HOWTO - BEGINNING PYTHON 36routine (middle right). This isneeded for every Kivy app.

This looks rather confusing.Unfortunately, the editor doesn’talways keep spaces correct even ina mono-spaced font. The idea isthat the text1 string is a simplescale starting with the note “C”.Each should be centered within 5spaces. Like the text shownbottom right.

The text2 string should be thesame thing but repeated. We willuse an offset into the text2 stringto fill in the button text within thescrollview widget.

Now we create the root object(which is our main window)containing a GridLayout widget. Ifyou remember WAY back when wewere doing other GUIdevelopment for Glade, there wasa grid view widget. Well, theGridLayout here is pretty much thesame. In this case, we have a gridthat has one column and threerows. In each of the cells created inthe grid, we can put other widgets.Remember, we can’t define whichwidget goes where other than inthe order in which we place thewidgets.

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

In this case, the representationis as follows....

­­­­­­­­­­­­­­­­­­­­­­­­­­­­­(0) title label­­­­­­­­­­­­­­­­­­­­­­­­­­­­­(1) main button­­­­­­­­­­­­­­­­­­­­­­­­­­­­­(2) scrollview­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

The scrollview contains multipleitems – in our case buttons. Next,we create the label which will be atthe top of our application.

lbl = Label(text='TransposerVer 0.1',

font_size=20,size_hint=(None,None),size=(480,20),padding=(10,10))

The properties that are setshould be fairly self-explanatory.The only ones that might give yousome trouble would be the

padding and size_hint properties.The padding is the number ofpixels around the item in an x,yreference. Taken directly from theKivy documentation size_hint (forX which is same as Y) is defined as:

����� ����� ���������� �������

����� ��������� ��������� �� ���

��������� ����� ������ �������� �� ���

�������������� �������������

���������� ��� ����� ����� ���

����� �� �� ��������� � ��������� ��

�� ��� ����� �� ����� ��� ���� ���� ��

��� ������� ��� ��������������

In this case, size_hint is set tonone, which defaults to 100% or 1.This will be more important (andconvoluted) later on.

Now we define our “main”button (next page, top right). Thisis a static reference for the scale.

Again, most of this should be

import kivykivy.require('1.0.8')from sys import exitfrom kivy.app import Appfrom kivy.core.window import Windowfrom kivy.uix.button import Buttonfrom kivy.uix.label import Labelfrom kivy.uix.anchorlayout import AnchorLayoutfrom kivy.uix.scrollview import ScrollViewfrom kivy.uix.gridlayout import GridLayout

def build(self):#­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­text1 = " C C#/Db D D#/Eb E F F#/Gb G G#/Ab A A#/Bb B C"text2 = " C C#/Db D D#/Eb E F F#/Gb G G#/Ab A A#/Bb B C C#/Db D

D#/Eb E F F#/Gb G G#/Ab A A#/Bb B C C#/Db"#­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

| | | | | | | | | | | |12345678901234567890123456789012345678901234567890123456C C#/Db E F F#/Gb G G#/Ab A A#/Bb B C

Page 17: PROGRAM IN PYTHON

full circle magazine #64 9 �������� �

Greg is the owner of RainyDaySolutions, LLC, a consulting companyin Aurora, Colorado, and has beenprogramming since 1972. He enjoyscooking, hiking, music, and spendingtime with his family. His website iswww.thedesignatedgeek.net.

HOWTO - BEGINNING PYTHON 36fairly clear.

Now we add the widgets to theroot object, which is theGridLayout widget. The label (lbl)goes in the first cell, the button(btn1) goes in the second.

#­­­­­­­­­­­­­­­­­­­­­­­­­­­­root.add_widget(lbl)root.add_widget(btn1)#­­­­­­­­­­­­­­­­­­­­­­­­­­­­

Now comes some harder-to-understand code. We createanother GridLayout object and callit “s”. We then bind it to the heightof the next widget which, in thiscase, will be the ScrollView, NOTthe buttons.

s = GridLayout(cols=1,spacing = 10, size_hint_y =None)s.bind(minimum_height=s.setter('height'))

Now (middle right) we create20 buttons, fill in the textproperty, and then add it to theGridLayout.

Now we create the ScrollView,set its size, and add it to the rootGridLayout.

sv =ScrollView(size_hint=(None,

None), size=(600,400))

sv.center = Window.center

root.add_widget(sv)

Lastly, we add the GridLayoutthat holds all our buttonsinto the ScrollView, andreturn the root object tothe application.

sv.add_widget(s)

return root

Finally, we have our “if__name__” routine. Noticethat we are settingourselves up for thepossibility of using theapplication as an androidapp.

if __name__ in('__main__','__android__'):

Transpose().run()

Now you might wonder why Iused buttons instead of labels forall our textual objects. That’sbecause labels in Kivy don’t haveany kind of visible border bydefault. We will play with this inthe next installment. We will alsoadd an exit button and a little bitmore.

The source code can be foundon PasteBin athttp://pastebin.com/hsicnyt1

Until next time, enjoy and thankyou for putting up with me forthree years!

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

for i in range(0,19):if i <= 12:

if i < 10:t1 = " " + str(i) + "| "

else:t1 = str(i) + "| "

else:t1 = ''text2 = ''

btn = Button(text = t1 + text2[(i*5):(i*5)+65],size=(680, 40),size_hint=(None,None),halign='left',font_name='data/fonts/DroidSansMono.ttf')

s.add_widget(btn)#­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

Page 18: PROGRAM IN PYTHON

full circle magazine #65 6�������� �

HHOOWW--TTOOWritten by Greg D. Walters PPrrooggrraammmmiinngg iinn PPyytthhoonn -- PPaarrtt 3377

Thismonth, we’ll finish upthe transposer programthat we wrote in Kivy.Hopefully, you saved the

code from last time, because we’llbe building upon it. If not, grab thecode from FCM#64.

Let’s start by recapping whatwe did last month. We created anapplication that allows for aguitarist to quickly transpose fromone key to the other. The ultimategoal is to be able to run this appnot only on your Linux or Windowsbox, but on an android device as

well. I take mine on my tabletwhenever I go to band practice. Iwas going to deal with packagingour project for Android, but somethings have changed in the methodto do that, so we’ll work on thatnext month.

The app, as we left it last time,looked like that shown below left.

When we are done, it shouldlook like the screen below right.

The first thing you will notice isthat there are blue labels rather

than boring gray ones. The next isthat there are three buttons.Finally the scrollable labels arecloser to the entire width of thewindow. Other than that, it’spretty much (visually) the same.One of the buttons is an “about”button that will pop up simpleinformation, but it explains how tomake a simple popup. One of thebuttons is an exit button. Theother button will swap the labeltext to make it easy to transposefrom piano to guitar or guitar topiano.

Let’s get started by creating a.kv file (above right). This is whatwill give us the colored labels. It’s avery simple file.

#:kivy 1.0#:import kivy kivy

<BoundedLabel>:canvas.before:Color:

rgb: 0, 0, 1Rectangle:

pos: self.possize: self.size

Page 19: PROGRAM IN PYTHON

full circle magazine #65 7�������� �

HOWTO - PROGRAMMING IN PYTHON 37The first two lines are required.

They basically say what version ofKivy to expect. Next we create anew type of label called‘BoundedLabel’. The color is setwith RGB values (between 0 and 1,which can be considered as 100percent), and as you can see theblue value is set at 100 percent.We will also create a rectanglewhich is the actual label. Save thisas “transpose.kv”. You must usethe name of the class that will beusing it.

Now that you have thatcompleted, add the following linesjust before the transpose class tothe source file from last time:

class BoundedLabel(Label):

pass

To make it work, all we need is adefinition. Before we go anyfurther, add the following line tothe import section:

from kivy.uix.popup importPopup

This allows us to create thepopup later on. Now, in theTranspose class, just inside the defbuild routine, place the codeshown above right.

The LoadLabels routine will giveus the colored labels(BoundedLabel) and the swapability. You saw most of this lasttime. We pass a value to the “w”parameter to determine which textis being displayed. Thel=BoundedLabel line is pretty muchthe same line from last time, withthe exception that, this time, weare using a BoundedLabel widgetinstead of a Button widget. TheLoadLabels will mainly be calledfrom the next routine, Swap. Placethis code (shown right) belowLoadLabels.

def LoadLabels(w):if w == 0:

tex0 = self.text1tex1 = self.text2

else:tex0 = self.text3tex1 = self.text4

for i in range(0,22):if i <= 12:

if i < 10:t1 = " " + str(i) + "| "

else:t1 = str(i) + "| "t = tex1

else:t1 = ''t = ''

l = BoundedLabel(text=t1+t[(i*6):(i*6)+78], size=(780, 35),size_hint=(None,None),halign='left',font_name='data/fonts/DroidSansMono.ttf')

s.add_widget(l)

def Swap(instance):if self.whichway == 0:

self.whichway = 1btnWhich.text = "Guitar ­­> Piano"btn1.text = " " + self.text3s.clear_widgets()LoadLabels(1)

else:self.whichway = 0btnWhich.text = "Piano ­­> Guitar"btn1.text = " " + self.text1s.clear_widgets()LoadLabels(0)

Page 20: PROGRAM IN PYTHON

full circle magazine #65 8 �������� �

HOWTO - PROGRAMMING IN PYTHON 37

You can see that this routine ispretty self explanatory. We use avariable (self.whichway) todetermine “which way” the labelsare displaying... from Guitar toPiano or Piano to Guitar.

Be sure to save your work atthis point, since we are going to bemaking a lot of changes from hereon.

Replace the lines defining text1and text two with the lines shownabove.

We set self.whichway to 0 whichwill be our default for the swapprocedure. Then we define fourstrings instead of the two we hadlast time. You might notice thatstrings text3 and text4 are simplereversals of text1 and text2.

Now we will tweak the root linedefinition. 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 spacingfrom 10 to 6 and set the defaultrow height to 40 pixels. Change thetext for the label (next line) to“text='Transposer Ver 0.8.0'”.Everything else stays the same onthis line.

Now change the buttondefinition line from...

btn1 = Button(text = " " +text1,size=(680,40),

size_hint=(None,None),

halign='left',

font_name='data/fonts/DroidSa

nsMono.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])

Notice that I’ve changed theformatting of the first definitionfor clarity. The big changes are thesize change from 680,40 to 780,20and the background color for thebutton. Remember, we can changethe background color for buttons,not “standard” labels.

Next, we will define three

AnchorLayout widgets for thethree buttons that we will add inlater. I named them al0(AnchorLayout0), al1 and al2. Wealso add the code for the AboutPopup, and define our buttonsalong with the bind statements.This is shown on the next page, topleft.

Find the “s = GridLayout” lineand change the spacing from 10 to4. Next, add the following lineafter the s.bind line (right beforethe for loop):

LoadLabels(0)

This calls the LoadLabelsroutine with our default “which” of0.

Next, comment out the entirefor loop code. This starts with “for iin range(0,19):” and ends with“s.add_widget(btn)”. We don’tneed this since the LoadLabelsroutine does this for us.

self.whichway=0

self.text1 = " C | B |A#/Bb| A |G#/Ab| G |F#/Gb| F | E |D#/Eb| D |C#/Db| C |"

self.text2 = " C | B |A#/Bb| A |G#/Ab| G |F#/Gb| F | E |D#/Eb| D |C#/Db| C | B |A#/Bb| A |G#/Ab| G |F#/Gb| F | E |D#/Ab| D |C#/Db| C |"

self.text3 = " C |C#/Db| D |D#/Eb| E | F |F#/Gb| G |G#/Ab| A |A#/Bb| B | C |"

self.text4 = " C |C#/Db| D |D#/Eb| E | F |F#/Gb| G |G#/Ab| A |A#/Bb| B | C |C#/Db| D |D#/Eb| E | F |F#/Gb| G |G#/Ab| A |A#/Bb| B | C |C#/Db|"

Page 21: PROGRAM IN PYTHON

full circle magazine #65 9 �������� �

Greg is the owner of RainyDaySolutions, LLC, a consulting companyin Aurora, Colorado, and has beenprogramming since 1972. He enjoyscooking, hiking, music, and spendingtime with his family. His website iswww.thedesignatedgeek.net.

HOWTO - PROGRAMMING IN PYTHON 37

Now, save your code and try torun it. You should see a deeppurple button at the top, and ourpretty blue BoundLabels. Plus, youwill notice that the BoundLabels inthe scroll window are closertogether, which makes it mucheasier to read.

We are almost through with ourcode, but we still have a few thingsto do. After the “sv = ScrollView”line add the following line...

sv.size = (720, 320)

This sets the size of theScrollView widget to 720 by 320 –which makes it wider within theroot window. Now, before the“return root” line, add the code

shown top right.

Here we add the three buttonsto the AnchorLayout widgets,create a GridLayout to hold theAnchorLayouts, and then finallyadd the AnchorLayouts to theGridLayout.

Go back just below the “defSwap” routine and add thefollowing...

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. Justclick anywhere outside of thepopup to make it go away.

Now our code is written. Youcan find the full code athttp://pastebin.com/GftmjENs

Next, we need to create ourandroid package... but that willhave to wait for next time.

If you want to get set up and trypackaging for Android before nextmonth, you should go tohttp://kivy.org/docs/guide/packaging-android.html for the

documentation on this. Be sure tofollow the documentationcarefully.

See you next month.

al0 = AnchorLayout()al1 = AnchorLayout()al2 = AnchorLayout()popup = Popup(title='About Transposer',

content=Label(text='Written by G.D. Walters'),size_hint=(None,None),size=(400,400))

btnWhich = Button(text = "Piano ­­> Guitar",size=(180,40),size_hint=(None,None))

btnWhich.bind(on_release=Swap)btnAbout = Button(text="About",size=(180,40),

size_hint=(None,None))btnAbout.bind(on_release=ShowAbout)btnExit = Button(text="Exit", size=(180,40),

size_hint=(None,None))btnExit.bind(on_release=exit)

al0.add_widget(btnWhich)al1.add_widget(btnExit)al2.add_widget(btnAbout)bgl = GridLayout(orientation='vertical',

spacing=6, cols=3,rows=1,row_default_height=40)

bgl.add_widget(al0)bgl.add_widget(al1)bgl.add_widget(al2)

Page 22: PROGRAM IN PYTHON

full circle magazine #67 8 �������� �

HHOOWW--TTOOWritten by Greg Walters PPrrooggrraammmmiinngg IInn PPyytthhoonn:: PPtt 3388

AsIpromised in part 37,we will take thetransposer app that wecreated, and create an

APK to install it on your androiddevice.

Before we get started, let’smake sure we have everythingready. First thing we need is thetwo files we created last time in afolder that you can easily access.Let’s call it “transposer”. Create itin your home directory. Next, copythe two files (transpose.kv andtranspose.py) into that folder. Nowrename transpose.py to main.py.This part is important.

Next, we need to reference thekivy packaging instructions in aweb browser. The link ishttp://kivy.org/docs/guide/packaging-android.html. We will be usingthis for the next steps, but notexactly as the Kivy peopleintended. You should have theandroid SDK from our earlierlesson. Ideally, you will go throughand get all the software that islisted there, but for our purposes,you can just follow along here. You

will need to download the python-for-android software. Open aterminal window and type thefollowing...

git clonegit://github.com/kivy/python-for-android

This will download and set upthe software that we need tocontinue. Now, in a terminalwindow, change your directory tothe python-for-android/dist/default folder.

Now you will find a file calledbuild.py. This is what will do all thework for us. Now comes the magic.

The build.py program will takevarious command-line argumentsand create the APK for you. Shownabove is the syntax for build.py

taken directly from the Kivydocumentation.

For our use, we will use thefollowing command (the “\” is aline continuation character):

./build.py --dir ~/transposer--packageorg.RainyDay.transposer \--name "RainyDay Transposer"

--version 1.0.0 debug

Let’s look at the pieces of thecommand...

./build.py - this is the application--dir ~/transposer - this is thedirectory where our applicationcode lives.--packageorg.RainyDay.transposer - This isthe name of the package--name “RainyDay Transposer” -

this is the name of the applicationthat will show up in the appsdrawer.--version 1.0.0 - the version of ourapplicationdebug - this is the level of release(debug or release)

Once you execute this,assuming that everything workedas expected, you should have anumber of files in the /bin folder.The one you are looking for istitled “RainyDayTransposer-1.0.0-debug.apk”. You can copy this toyour android device using yourfavorite file manager app, andinstall it just like any otherapplication from the various appstores.

That’s all I have time for thismonth.

./build.py --dir <path to your app>--name "<title>"--package <org.of.your.app>--version <human version>--icon <path to an icon to use>--orientation <landscape|portrait>--permission <android permission like VIBRATE> (multiple allowed)<debug|release> <installd|installr|...>