issuePY06 en

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

Full Circle

THE INDEPENDENT MAGAZINE FOR THE UBUNTU LINUX COMMUNITY

PROGRAMMING SERIES SPECIAL EDITION

PROGRAM
IN PYTHON
Volume Six
Parts 32-38
Full Circle Magazine is neither affiliated, with nor endorsed by, Canonical Ltd.
Full Circle Magazine Specials
About Full Circle
Full Circle is a free, Find Us
independent, magazine Website:
dedicated to the Ubuntu http://www.fullcirclemagazine.org/
family of Linux operating
systems. Each month, it Forums:
contains helpful how-to http://ubuntuforums.org/
articles and reader- forumdisplay.php?f=270
submitted stories. Welcome to another 'single-topic special' IRC: #fullcirclemagazine on
Full Circle also features a In response to reader requests, we are assembling the chat.freenode.net
companion podcast, the Full content of some of our serialised articles into dedicated Editorial Team
Circle Podcast which covers
editions. Editor: Ronnie Tucker
the magazine, along with
other news of interest. For now, this is a straight reprint of the series (aka: RonnieTucker)
'Programming in Python', Parts 27-31 from issues #60 ronnie@fullcirclemagazine.org

Please note: this Special through #67, allowing peerless Python professor Gregg Webmaster: Rob Kerfia
Edition is provided with Walters #66 as time off for good behaviour. (aka: admin / linuxgeekery-
absolutely no warranty admin@fullcirclemagazine.org
Please bear in mind the original publication date; current
whatsoever; neither the Editing & Proofreading
contributors nor Full Circle versions of hardware and software may differ from those
Mike Kennedy, Lucas Westermann,
Magazine accept any illustrated, so check your hardware and software versions Gord Campbell, Robert Orsino,
responsibility or liability for before attempting to emulate the tutorials in these special Josh Hertel, Bert Jerred
loss or damage resulting from editions. You may have later versions of software installed
readers choosing to apply this Our thanks go to Canonical and the
or available in your distributions' repositories.
content to theirs or others many translation teams around the
computers and equipment. Enjoy! world.

The articles contained in this magazine are released under the Creative Commons Attribution-Share Alike 3.0
Unported 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.

full circle magazine


HOW-TO
Written by Greg D. Walters
Beginning Python - Part 32

I
must say, I love my Android something like “Well, if you REALLY friends on facebook, and play Python programming for the
tablet. While I use it every day, think we need that...”. Then she games - all on a device that was Android Operating system. One of
it's not yet a replacement for gives me the same look I give her light and cool. If she got tired, she these tools is called “SL4A”. SL4A
my desktop. And I must also as she is lovingly fondles the 50th could just slip it off to the side stands for Scripting Layer for
admit, most of what I use it for is pair of shoes at the store. between her and the recliner (or Android. That's what we will
pretty much what everyone uses In all honesty, it wasn't hard to bed when she was home trying to concentrate on in the next couple
theirs for: web browsing, listening get the first tablet into our house. I regain strength). MUCH better than of articles. We'll really focus on
to music, watching videos, playing bought it for my wife while she was a bulky laptop, and book, mp3 getting SL4A set up on Android in
games, and so on. I try to justify it going through chemotherapy. She player, remote control, and more. this one.
by having apps that deal with tried to use a laptop for a while,
grocery and todo lists, finding but the heat and weight on As she was getting You might ask, why in the world
cheap gas, fun things for our her lap was too much pumped full of noxious I would be talking about Android
grandson, etc. It's really a toy for after a while. E-books chemicals, I would programming in a magazine
me right now. Why use a fancy on a laptop for her commandeer a designed for Linux. Well, the
touch-screen tablet to do your wasn't an option, table and chair in simple reason is that the core of
grocery list? Let's face it... it's the so when she tried the corner of the Android is Linux. Everything that
cool looks of envy that people give to read, she had treatment Android is, sits on top of Linux!
me in the store when they see me to juggle the room, near a
rolling the cart down the aisle and I book, and the power outlet, Many web pages show how to
tap my tablet to mark items off the laptop, and the and try to work load SL4A into the Android
list. Ahh--- the geek factor RULES! mp3 player. All on my six-year Emulator for Desktops. We'll look
Of course, I can use the back of an while being tied old laptop. In at doing that another time, but for
old envelope to hold my list. But to a recliner with between now we'll deal with the Android
that wouldn't be cool and geeky, tubes running into projects, I would device itself. To install SL4A on
now, would it? her arm filling her do research on your Android device, go to
with nasty chemicals. Android http://code.google.com/p/android-
Like 99% of geeky married men When I got her the programming. I found scripting/; you'll find the
in the world, I am married to a non- tablet, it was the best of all out that most programming installation file for SL4A. Don't be
geek woman. A wonderful loving worlds. She could read an e-book, for Android is done in Java. I had absolutely confused here. There's a
woman, to be sure, but a non-geek listen to music, watch a TV show, almost resigned myself to re- square High Density barcode that
who, when I start drooling at the browse the web, check her E-mail, learning Java when I stumbled you tap to download the APK. Be
latest gadget, sighs, and says update her cancer blog, follow her across a few tools that allow sure that you have the “Unknown

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


HOWTO - BEGINNING PYTHON 32
Sources” option enabled in the
Application settings. It's a quick ������ ��� � ������ How to Include Accents from the Keyboard


download. Once you have it ������������� ����� by Barry Smith

I
downloaded and installed, go ������ ����� ������
ahead and find the icon, and tap it. ��� f your Linux system is in French, German, or Spanish, and,
What you will see is a rather therefore, requiring accents, or if, occasionally, you need to use
disappointing black screen saying accents which do not appear in English words, many users do not
“Scripts...No matches found”. know that there is a very easy way to do this from the keyboard.
That's OK. Hit the menu button and The following applies to only the UK keyboard.
select View. You'll see a menu. http://developer.android.com/sdk/i
Select Interpreters. Then select ndex.html to get the Android SDK Acute accent
menu again, and select Add. From (Software Development Kit) for Press Alt Gr + ; (semi-colon) Lift hand then press the desired vowel é
the next menu, select Python 2.6.2. your desktop. It includes an
This should ask you to start a Android Emulator so you can play Circumflex
browser session to download along. Setting up the SDK is really Press Alt Gr + ' (apostrophe) Lift hand then press the desired vowel î
Python for Android. Once this is pretty easy on Linux, so you
installed, select Open. You'll get a shouldn't have too much trouble. Grave accent
screen menu with the options to Press Alt Gr + # (hache) Lift hand then press the desired vowel è
Install, Import Modules, Browse
Modules, and Uninstall modules. Umlaut
Select Install. Now Python will Press Alt Gr + [ Lift hand then press u ü
download and install along with
other extra modules. In addition, ñ - Press Alt Gr + ] Lift hand then press n ñ
you'll get some sample scripts.
Finally, tap the back button and œ - Press Shift + Alt Gr Lift hand then press o then press e œ
you'll see Python 2.6.2 installed in The œ will not appear until after the e is keyed.
the interpreters screen. Tap again
on the back button and you'll see a To get ¿ and ¡ (inverted exclamation mark) which I use all the time in
list of some sample python scripts. Spanish before questions, and exclamations, press Alt Gr + Shift,
Greg is the owner of RainyDay keeping both keys pressed, then hit _ (underscore) for ¿ or hit !
That's all we are going to do this Solutions, LLC, a consulting company (exclamation mark) for ¡.
time. All I wanted to do is whet in Aurora, Colorado, and has been
programming since 1972. He enjoys
your appetite. Explore Python on cooking, hiking, music, and spending If you want any of these in capitals, just press Shift before keying in
Android. You might also want to time with his family. His website is the letter.
visit www.thedesignatedgeek.net.

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


HOW-TO
Written by Greg D. Walters
Beginning Python - Part 33

T
his time, we’ll set up the over to Save the file and move on to and update the platforms that are
Android SDK on our Linux http://developer.android.com/sdk/i step 2. available. I will warn you now that
desktop. We’ll also create nstalling.html to see all the steps this process will take some time, so
a virtual Android device, in the suggested order. Let’s get don’t bother if you don’t have a lot
install SL4A and python on it, and started. STEP 2 - Android SDK of time to deal with it. For the sake
do a quick test. Starter Pack of brevity, I would suggest you get
STEP 1 - Java JDK 6 only one platform to start. A good
Please be aware, this is not Now the actual “fun” begins. one to begin with is the Android
something you would want to do From everything I’ve read and You’ll want to go to 2.1 platform, since, for the most
for machines that have less than 1 tried, it must be the actual Sun developer.android.com/sdk/index. part, if you develop for an older
GB of ram. The emulator eats up a release. OpenJDK is not supposed html. This is where the SDK is platform, there should be no
huge amount of memory. I’ve tried to work. You can find information located. Download the latest problem running on a newer
it on a laptop running Ubuntu with on this on the web, but here’s the version for Linux, which, at the platform. You also need to get the
only 512 MB of ram. It WILL work, steps that I did. In a terminal, type time of this writing, is android- Tools set as well. Simply check the
but it is REALLY slow. the following... sdk_r18-linux.tgz. Using Archive box next to those two items, then
Manager, unpack it somewhere click on the install button. Once
Here’s a quick list of what we’ll sudo add­apt­repository convenient. I put it in my home you get the platform of your
do. We’ll go step-by-step in a ppa:ferramroberto/java directory. Everything runs directly choice, and the tool set, you are
minute. from this folder, so you really don’t almost ready to create your first
• Install the Java JDK6. sudo apt­get update have to install anything. So the virtual machine.
• Install the Android SDK starter path for me is
sudo apt­get install sun­
pack. java6­jdk /home/greg/android-sdk-linux. STEP 3 - Create and set
• Create and setup AVDs. Navigate to this folder, then go to
• Test AVD, and install SL4A and the tools folder. There you will find up your first AVD
Once everything here is done,
Python. you will want to edit your .bashrc a file called “android”. This is what
runs the actual SDK. I created a Back in the Android SDK
file to set “JAVA_HOME” so Manager, select Tools from the
In reality, we should also install everything runs correctly. I used launcher on my desktop to make it
easy to get to. main menu, then select Manage
Eclipse and the Android ADT plugin gedit and, at the bottom of the AVDs. This will open a new window.
for Eclipse, but, since we won’t be file, I added the following line...
Now the boring part. Run the Since this is the first time, there
dealing with Eclipse in this set of
android file, and the Android SDK won’t be any virtual devices set up.
articles, we can bypass that. If you export
JAVA_HOME=”/usr/lib/jvm/java­ Manager will start. It will go out Click on the “New” button. This
want to include those steps, head
6­sun­1.6.0.06” opens yet another window where
full circle magazine #61 7 �������� �
HOWTO - BEGINNING PYTHON 33
we define the properties of the button. In the dialog box that pops make your programming transition Home - Home
virtual Android device. Here’s the up, simply click the “Launch” easier. You’ll see the download Menu - F2
steps that you should use to set up button. Now, you have to wait a start. You may have to pull down
a simple Android emulator device: few minutes for the virtual device the notification bar at the top to Now we will want to download
• Set the name of the device. This to be created in memory, and the get to the downloaded file. Tap on and install python into SL4A. To do
is important if you have more than Android platform to be that, then tap the install this, first tap Menu (press F2).
one device. loaded and started. button. Select “View” from the menu. Now
• Set the target platform level. (We’ll talk about select “Interpreters”. It looks like
• Set the size of the SD card (see speeding this Once the file is nothing happened, but tap Menu
below). process up in downloaded, again (F2), then select “Add” from
• Set the skin resolution. later runs.) you’ll be the popup. Now scroll down and
• Create the device. presented with select “Python 2.6.2”. This will
Once the the option to download the base package for
So, In the name text box, type AVD starts up open the Python for Android. Install the
“Test1”. Under the target combo- and you have downloaded package, then open it. You will be
box, select Android 2.1 - API Level the “home” app or to tap presented with four options.
7. In the text box for “SD Card:” screen up, you “Done” to exit Install, Import Modules, Browse
enter 512 and make sure the will install SL4A. the installer. Modules, and Uninstall Module.
dropdown shows “MiB”. Under Using the Here we will want Tap on Install. This will start
“Skin”, set the resolution to browser or the to tap “Open”. downloading and installing all the
800x600. (You can play with the google web search pieces of the latest Python for
other built-in sizes on your own.) box on the home screen, Now SL4A will start. Android. This can take a few
Finally, click the “Create AVD” search for “sl4a”. Go to the You’ll probably see a dialog minutes.
button. Soon, you’ll see a message downloads page, and you’ll asking if you will agree to usage
box saying that the AVD was eventually find the web page for tracking. Either accept or refuse Once everything is done, tap
created. the downloads at this - it’s up to you. Before we go Back (escape key) until you get to
http://code.google.com/p/android- any farther, you should know some the SL4A Interpreters screen. Now
scripting/downloads/list. keyboard shortcuts that will help everything is loaded for us to play
STEP 4 - Testing the
you move around. Since we don’t in Python on Android. Tap Python
AVD and installing Scroll down the page until you have a “real” Android device, 2.6.2, and you’ll be in the
SL4A and Python get to the sl4a_r5 link. Open the buttons like Back, Home, and “standard” Python shell. This is just
link and tap on the “sl4a_r5.apk” Menu, aren’t available. You’ll need like the shell on your desktop. Type
Now, finally, we can have a bit link. Notice I said “tap” rather than them to navigate around. Here’s a the following three lines, one at a
of fun. Highlight the AVD you just “click”. Start thinking about using few important shortcuts. time, into the shell. Be sure to wait
created and click on the Start your finger to tap the screen rather for the “>>>” prompt each time.
than clicking the mouse. It will Back - Escape
full circle magazine #61 8 �������� �
HOWTO - BEGINNING PYTHON 33
import android You should be presented with the Name the file andtest1.py, then
sample scripts that come with tap Done, and tap “Save & Run”. If
droid = android.Android() Python 4 Android. Tap the Menu everything worked, you should see
button and select “Add”. Select a dialog box asking for your name.
droid.makeToast(“Hello from
Python on Android”) “Python 2.6.2” from the list. You’ll After you enter it, you should see
be presented with the script editor. the alert at the bottom of the O'Reilly are looking forward to
After you type the last line and At the top is the filename box with screen saying “Hello Your Name
celebrating Velocity's 5th Year with you
“.py” already filled out. Below that June 25-27, at the Santa Clara
press Enter, you’ll see a rounded from Python on Android”. Convention Center. You'll meet the
corner box at the center bottom of is the editor window that already smartest people working in web
the shell that says “Hello from has the first two lines of our That’s all for this time. For now, performance and operations at the
Python on Android”. That’s what program entered for us. (I included there’s a TON of documentation
O'Reilly Velocity Conference. Web and
them below in italics so you can mobile users expect better
the “droid.makeToast” command about SL4A for free on the web. performance than ever before. To
does. check it. We also used these two You can play a bit on your own until meet, and exceed, their expectations,
lines in our first sample.) next time. I’d suggest that you you need to master a daunting array of
web performance, operations, and
You’ve written your first Python start by going to
import android mobile performance issues. Velocity
script for Android. Neat, huh? http://code.google.com/p/android- offers the best opportunity to learn the
droid = android.Android() scripting/wiki/Tutorials. newest info on what you need to know
Now let’s create a shortcut on to build a faster and stronger web.
the Android home screen. Tap the Now, enter the following two Take advantage of this rare opportunity
Home key (Home button). If you lines to the python script. to meet face-to-face with a cadre of
chose the 2.1 platform, you should industry leaders who are taking web
see a slider bar on the far right of uname = performance and operations to the
next level. Velocity packs a wealth of
the screen. If you chose another droid.dialogGetInput(“What’s
your name?”) big ideas, know-how, and connections
platform, it might be a square or into three concentrated days. You'll be
rectangle consisting of small able to apply what you've learned
droid.makeToast(“Hello %s immediately and you'll be well
squares. Either way, this gets you from Python on Android”) % prepared for what lies ahead with four
to the Apps screen. Tap that, and uname.result in-depth tracks covering the key
find the SL4A icon. Now perform a aspects of web performance,
“long tap” (long click), which will The first new line will create a operations, mobile performance, and
create a shortcut on the Home dialog box (droid.dialogGetInput()) Greg is the owner of RainyDay Velocity culture.
screen. Move the shortcut Solutions, LLC, a consulting company
that asks for the user’s name. The in Aurora, Colorado, and has been Velocity has sold out the last two years,
wherever you want it. response is returned to our programming since 1972. He enjoys so if you want to reserve your spot at
program in uname.result. We’ve cooking, hiking, music, and spending Velocity 2012, register now and save an
Next, we will create our first already used the droid.makeToast() time with his family. His website is additional 20% with code FULLCIR.
saved script. Go back into SL4A. www.thedesignatedgeek.net.
function.

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


HOW-TO
Written by Greg D. Walters
Beginning Python - Part 34

T
his time, we’ll finish up
import android
using SL4A. We’ll make a
larger program and then droid = android.Android()
send it to the virtual uname = droid.dialogGetInput("Hello","What's your name?")
machine via ADB. droid.makeToast("Hello %s from python on Android!" % uname.result)

Let’s deal with our code first. In


this, we’ll simply be trying out droid.dialogCreateAlert(uname.result,"Would you like to play a game?")
some of the “widgets” that are droid.dialogSetPositiveButtonText('Yes')
available to us when using SL4A. droid.dialogSetNegativeButtonText('No')
Start on your desktop using your droid.dialogShow()
while True: #wait for events for up to 10 seconds...
favorite editor. response = droid.eventWait(10000).result
if response == None:
Enter the code shown top right break
and save it (but don’t try to run it) if response["name"] == "dialog":
break
as “atest.py”. droid.dialogDismiss()

The first line imports the


android library. We create an code (above). buttons, one with the text “Yes”, droid.eventWait(value) call. The
instance of it in the second line. which is a “positive” button, and response (either “positive” or
Line 3 creates and displays a dialog Save your code as atest1.py. one with the text “No”, a “negative”) will be returned in -
box with the title “Hello”, the We’ll be sending this to our virtual “negative” button. The positive you guessed it - the response
prompt of “What’s your name?”, a machine after we discuss what it and negative buttons refer to the variable. If response has the name
text box for the user to enter their does. response returned - either of “dialog”, then we will break out
name, and two buttons, “OK” and “positive” or “negative”. The next of the loop and return the
“Cancel”. Once the user presses Take a look at the first four lines line then shows the dialog. The response. If nothing happens
“OK”, the response is returned in we just entered. We create an alert next seven lines wait for a before the timeout occurs, we
the variable uname. The last line type dialog asking “Would you like response from the user. simply break out of the loop. The
(so far) then says “Hello to play a game?”. In the case of an actual information returned in the
{username} from python on alert type dialog, there’s no text We create a simple loop (while response variable is something like
Android!”. This isn’t new, we did box to enter anything. The next True:) then wait for a response for this (assuming the “positive” or
this before. Now we’ll add more two lines say to create two up to 10 seconds by using the “Yes” button is pressed)...

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


HOWTO - BEGINNING PYTHON 34
{u’data’: {u’which’: emulator but also any should see atest1.py. Tap
u’positive’}, u’name’: smartphones, tablets, or other (click) on ‘atest1.py’, and if response==None:
u’dialog’, u’time’: Android devices. You should see you’ll see a popup dialog with print "Timed out."
1339021661398000.0} else:
something like this... 6 icons. From left to right, rdialog=response["data"]
they are “Run in a dialog
You can see that the value is List of devices attached window”, “Run outside of a
passed in the ‘data’ dictionary, the emulator­5554 device
window”, “Edit”, “Save”, this set of code simply checks the
dialog key is in the ‘name’
“Delete”, and “Open in an external response, and, if it’s ‘None’ due to
dictionary, and there is a ‘time’ Now that we are sure that our
editor”. Right now, tap (click) on a timeout, we simply print “Timed
value that we don’t care about device is attached, we want to
the far left icon “Run in a dialog out.” And, if it’s actually something
here. push the application to the device.
window” so you can see what we want, then we assign the data
The syntax is...
happens. to the variable rdialog. Now add
Finally we dismiss the dialog
box. adb push source_filename the next bit of code (below)...
destination_path_and_filename You’ll see the first dialog asking
for your name. Enter something in This part of the code will look at
Before we can send our code to
So, in my case it would be... the box and tap (click) the ‘Ok’ the data passed back by the
the virtual machine, we have to
button. You’ll see the hello button-press event. We check to
start the virtual machine. Start
adb push atest1.py message. Next, you’ll see the alert see if the response has a “which”
your Android emulator. Once it /sdcard/sl4a/scripts/atest1.p dialog. Tap (click) on either button key, and, if so, it’s a legitimate
starts up, notice that the title bar y
to dismiss the dialog. We aren’t button press for us. We then check
has four digits at the start of the
If everything works correctly, looking at the responses yet so it to see if the result is a “positive”
title. This is the port that the
you’ll get a rather disappointing doesn’t matter which one you (‘Ok’ button) response. If so, we’ll
machine is listening on. In my case
message similar to this... choose. Now we’ll add some more create another alert dialog, but
(and probably yours) it’s 5554.
code (top right). this time, we will add a list of items
11 KB/s (570 bytes in 0.046s) for the user to choose from. In this
Now, let’s push it to our virtual
I’m sure you can figure out that case, we offer the user to select
machine. Open a terminal window
and change to the folder you saved Now, on
the code in. Assuming you have set the Android
emulator, if rdialog.has_key("which"):
your path to include the SDK, type result=rdialog["which"]
start SL4A.
if result=="positive":
adb devices You should droid.dialogCreateAlert("Play a Game","Select a game to play")
see all of the droid.dialogSetItems(['Checkers','Chess','Hangman','Thermal
This asks adb to show any python Nuclear War']) # 0,1,2,3
scripts, and, droid.dialogShow()
devices that are connected. This resp = droid.dialogGetResponse()
can include not only the Android in there you

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


HOWTO - BEGINNING PYTHON 34
from a list including Checkers,
Chess, Hangman, and Thermal if resp.result.has_key("item"):
sel = resp.result['item']
Nuclear War, and we assign the if sel == 0:
values 0 to 3 to each item. (Is this droid.makeToast("Enjoy your checkers game")
starting to seem familiar? Yes, it’s elif sel == 1:
from a movie.) We then display the droid.makeToast("I like Chess")
elif sel == 2:
dialog and wait for a response. The droid.makeToast("Want to 'hang around' for a while?")
part of the response we are else:
interested in is in the form of a droid.makeToast("The only way to win is not to play...")
dictionary. Assuming the user
tapped (clicked) on Chess, the
the returned data. The selection is
resulting response comes back like
#1 and is held in the ‘item’ key. elif result=="negative":
this...
Here’s the next part of the code droid.makeToast("Sorry. See you later.")
(above right)... elif rdialog.has_key("canceled"):
Result(id=12,
print "Sorry you can't make up your mind."
result={u’item’:1},
else:
error=None) Here we check to see if the print "unknown response=",response
response has the key “item”, and, if print "Done"
In this case, we are really so, assign it to the variable “sel”.
interested in the result portion of Now we use an if/elif/else loop to
check the values and deal with the ability to make “GUIfied” As usual, the code has been put
whichever is selected. We use the applications, but not full gui apps. up on pastebin at
droid.makeToast function to This however, should not keep you http://pastebin.com/REkFYcSU
display our response. Of course, from going forward and starting to
you could add your own code here. write your own programs for See you next time.
Now for the last of the code Android. Don’t expect to put these
(bottom right)... up on the “market”. Most people
really want full GUI type apps. We’ll
As you can see, we simply look at that next time. For more
respond to the other types of information on using SL4A, simply
Greg is the owner of RainyDay
button-presses here. do a web search and you’ll find lots Solutions, LLC, a consulting company
of tutorials and more information. in Aurora, Colorado, and has been
Save, push, and run the programming since 1972. He enjoys
program. By the way, you can push cooking, hiking, music, and spending
time with his family. His website is
directly to your smartphone or www.thedesignatedgeek.net.
As you can see, SL4A gives you tablet in the same way.

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


HOW-TO
Written by Greg D. Walters
Beginning Python - Part 35

T
his time, we are going to new set of tools to make your GUI come with Kivy, and, next month, and you must always import App
take a short detour from programming. All that having been we’ll “roll our own”. from kivy.app.
our exploration of said, Kivy is also fairly complicated
Android programming, to deal with. You are limited to the Once you’ve unpacked Kivy into The next eight lines are the
and look at a new framework for widgets that they have provided. In its own folder, use a terminal and main application class. The class is
GUI programming called Kivy. addition, there is no GUI designer change to that folder. Mine is in defined, then a routine called build
You’ll want to head over to for Kivy, so you have to do a GREAT /home/greg/Kivy-1.3.0. Now is created. You will almost always
http://kivy.org and download and deal of pre-planning before you try change to the examples folder, have a build routine somewhere in
install the package – before to do anything complicated. Also then to the widgets folder. Let’s your Kivy programs. Next we set a
getting too far into this month’s remember, Kivy is continually look at the accordion_1.py root object from the Accordion
installment. The Ubuntu under development so things can example. widget. Next we create five
installation instructions can be change quickly. So far, I haven’t AccordionItems and set their title.
found at found any of my test code that has It’s very simple, but shows a We then add ten labels with the
http://kivy.org/docs/installation/in broken by a new version of Kivy, really neat widget. Below is their text “Very big content”. We then
stallation-ubuntu.html. but that’s always a possibility. code. add each label to the root widget
(the Accordion) and then finally we
First off, Kivy is an open source Rather than jump in and create As you can see, the first three return the root object. This, in
library that makes use of multi- our own code this month, we’ll lines are import statements. Any essence, displays the root object in
touch displays. If that isn’t cool look at some of the examples that widget you use must be imported, the window that Kivy creates for
enough, it’s also cross-platform,
which means that it will run on from kivy.uix.accordion import Accordion, AccordionItem
from kivy.uix.label import Label
Linux, Windows, Mac OSX, IOS and from kivy.app import App
Android. Now you can see why we
are talking about this. But class AccordionApp(App):
remember, for the most part, def build(self):
root = Accordion()
anything you code using Kivy, can for x in xrange(5):
run on any of the above platforms item = AccordionItem(title='Title %d' % x)
without recoding. item.add_widget(Label(text='Very big content\n' * 10))
root.add_widget(item)
return root
Before we go too far, let me
make a couple of statements. Kivy if __name__ == '__main__':
is VERY powerful. Kivy gives you a AccordionApp().run()

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


HOWTO - BEGINNING PYTHON 35
us. Finally we have the “if grid, and four buttons along the
from kivy.app import App
__name__” statement and then run bottom of the window. As you click from kivy.uix.label import Label
the application. (tap) each of the buttons, the from kivy.uix.gridlayout import GridLayout
alignment of the text within the from kivy.uix.floatlayout import FloatLayout
Go ahead and run it to see what red boxes will change. The main from kivy.properties import ObjectProperty
it does. reason you would want to pay
attention to this example is how to class Selector(FloatLayout): halign),
You will see that in a moment use and control some of the
app = ObjectProperty(None) size_hint=(None, None),
or two, a window opens up with important widgets as well as how
five vertical bars in it. Clicking on a to change the alignment in your halign=halign, valign=valign)
Now the Application class is
bar causes it to open up revealing widgets, which is not completely
created.
the ten labels. Of course, each bar intuitive. In the code above, an instance
has the same text in the ten labels, of the BoundedLabel widget is
Here the routine select is
but you can figure out how to fix Above right is their code for this created, once for each of the nine
created. A GridLayout widget is
that. one. I’ll break it into pieces. First red boxes. You might want to stop
created (called grid) which has 3
the import code (above right). here and say “But wait! There isn’t
rows and 3 columns. This grid is
The Accordion widget can be a BoundedLabel widget. It just has
going to hold the nine red boxes.
used for any number of things, but Below is something special. a pass statement in it.” Well, yes,
the thing that has always jumped They created a class with no code for valign in ('bottom', and no. We are creating an
to my mind is for a configuration in it. I’ll discuss that in a few 'middle', 'top'): instance of a custom widget. As I
screen... each bar being a different minutes: said a little bit above, we’ll talk
configuration set. for halign in ('left',
'center', 'right'): more about that in a minute.
class BoundedLabel(Label):
Next we’ll look at the pass In the code block (top right,
Here we have two loops, one
textalign.py example. It’s not as next page), we examine the
inner and one outer.
“sexy” as the last one, but it’s a Next a class called “Selector” variable ‘case’ which is passed into
good example that gives you some (below) is created: label = BoundedLabel(text='V: the select routine.
important information for later on. %s\nH: %s' % (valign,

Before we look at the code, run class TextAlignApp(App):


the program. def select(self, case):

What you should see is a label grid = GridLayout(rows=3, cols=3, spacing=10, size_hint=(None, None),
at the top of the window, a set of pos_hint={'center_x': .5, 'center_y': .5})
nine red boxes with text in a 3x3
full circle magazine #63 8 �������� �
HOWTO - BEGINNING PYTHON 35
Here, the grid is removed, to folder that holds the .py file, you’ll
if case == 0:
clear the screen. notice another file called label.text_size = (None, None)
textalign.kv. This is a special file elif case == 1:
if self.grid: that Kivy uses to allow you to label.text_size = (label.width, None)
create your own widgets and rules. elif case == 2:
self.root.remove_widget(self. label.text_size = (None, label.height)
grid) When your Kivy application starts, else:
it looks in the same directory for label.text_size = label.size
The bind method here sets the the .kv helper file. If it is there, grid.add_widget(label)
size, and the grid is added to the then it loads it first. Here’s the
root object. code in the .kv file.
def build(self):
self.root = FloatLayout()
grid.bind(minimum_size=grid.s This first line tells Kivy what self.selector = Selector(app=self)
etter('size')) minimum version of Kivy that must self.root.add_widget(self.selector)
self.grid = None
be used to run this app.
self.grid = grid self.select(0)
return self.root
self.root.add_widget(grid) #:kivy 1.0

Here the BoundedLabel widget <BoundedLabel>:


Remember in the last example I canvas.before:
said that you will almost always is created. Each of the red boxes in Color:
use a build routine. Here is the one the application is a BoundedLabel. rgb: 1, 0, 0
for this example. The root object is Rectangle:
Color sets the background color pos: self.pos
created with a FloatLayout widget. size: self.size
Next (middle right) we call the of the box to red (rgb: 1,0,0). The
Selector class to create a Selector Rectangle widget creates a (you
the label across the top of the released, it calls (in this case)
object, then it’s added to the root guessed it) rectangle. When we call
window. root.app.select with a case value.
object, and we initialize the display the BoundedLabel widget in the
by calling self.select(0). actual application code, we are
Notice that the label that makes Hopefully, this is beginning to
passing a label as the parent. The
up the title at the top of the make sense now. You can see why
Finally the application is size and position (here in the .kv
window has a position (pos_hint) Kivy is so powerful.
allowed to run. file) are set to whatever the size
as top, has a height of 50 pixels
and position of the label are.
and a font size of 16. Each of the Let’s talk for a moment about
TextAlignApp().run()
buttons has an alignment for the two widgets that I have passed
Here (right, next page) the
text of center. The on_release over in the discussion of the
Now, before we can go any Selector widget is created. This is
statement is a bind-like statement application code, The GridLayout
further, we need to clear up a few the four buttons that appear at the
so that, when the button is and the FloatLayout.
things. First, if you look in the bottom of the window as well as
full circle magazine #63 9 �������� �
HOWTO - BEGINNING PYTHON 35
The GridLayout is a parent applications to Android.
<Selector>:
widget that uses a row and column Label:
description to allow widgets to be Until then, explore pos_hint: {'top': 1}
placed in each cell. In this case, it is more of the examples in size_hint_y: None
Kivy, and be sure to go to height: 50
a 3x3 grid (like a Tic-Tac-Toe (or font_size: 16
Naughts and Crosses) board). the documentation page
text: 'Demonstration of text valign and halign'
for Kivy at BoxLayout:
__|__|__ http://kivy.org/docs/. size_hint_y: None
__|__|__ height: 50
| | ToggleButton:
halign: 'center'
When you want to place a group: 'case'
text: 'label.text_size =\n(None, None)'
widget into a GridLayout, you use
on_release: root.app.select(0)
the add_widget method. Here lies state: 'down'
a problem. You can’t specify which ToggleButton:
control goes into which grid cell halign: 'center'
group: 'case'
other than the order in which you
text: 'label.text_size =\n(label.width, None)'
add them. In addition, each widget on_release: root.app.select(1)
is added from left to right, top to ToggleButton:
bottom. You can’t have an empty halign: 'center'
group: 'case'
cell. Of course, you can cheat. I’ll
text: 'label.text_size =\n(None, label.height)'
leave that up to you to figure out. on_release: root.app.select(2)
ToggleButton:
The FloatLayout widget seems halign: 'center'
group: 'case'
to be just a parent container for
text: 'label.text_size =\n(label.width, label.height)'
other child widgets. on_release: root.app.select(3)

I’ve glossed over a few points


for now. My intent this time was
simply to get you somewhat
Greg is the owner of RainyDay
excited about the possibilities that
Solutions, LLC, a consulting company
Kivy has to offer. In the next in Aurora, Colorado, and has been
couple of articles, we’ll continue to programming since 1972. He enjoys
explore what Kivy has for us, how cooking, hiking, music, and spending
time with his family. His website is
to use various widgets, and how to
www.thedesignatedgeek.net.
create an APK to publish our

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


HOW-TO
Written by Greg D. Walters
Beginning Python - Part 36

B
efore I begin, I want to Imagine you play guitar. Not air example, the chord is F# minor and Now we’ll add
note that this article guitar, but an actual guitar. you put the capo on fret 2, you can our import
marks three years of the However, you aren’t the best guitar simply play an E minor. But that statements
Beginning Programming player, and some chords are takes time. Let’s make an app that which are shown
using Python series. I want to problematical for you. For allows you to simply scroll through on the next page, top right.
thank Ronnie and the entire staff example, you know the standard C, the fret positions to find the
of Full Circle Magazine for all their E, G, F type chords, but some easiest chords to play. Notice the second line,
support and especially, you, the chords – like F# minor or C# minor “kivy.require(‘1.0.8’)”. This allows
readers. I NEVER thought that this – while doable, are hard to get your Our app will be fairly simple. A you to make sure that you can use
would continue this long. fingers set in a fast song. What do title label, a button with our basic the latest and greatest goodies
you do, especially if the gig is only scale as the text, a scrollview (a that Kivy provides. Also notice that
I also want to take a second to a couple of weeks away and you wonderful parent widget that we are including a system exit (line
note that there has been some HAVE to be up to speed TODAY? holds other controls and allows 3). We’ll eventually include an exit
comments floating around the The workaround for this is to use you to “fling” the inside of the button.
ether that, after three years, the the Capo (that funny clippy thing control to scroll) holding a number
word “Beginning” might be that you see sometimes on the of buttons that have repositioned Here is the beginning of our
misplaced in the title of this series. neck of the guitar). This raises the scales as the text, and an exit class called “Transpose”.
After all, after three years, would key of the guitar and you use button. It will look SOMETHING
you still be a beginner? Well, on different chords to match the rest like the text below. class Transpose(App):
some levels, I agree. However, I of the band. This is called
def exit(instance):
still get comments from readers transposing. Sometimes, you can Start with a new python file
saying that they just found the transpose on the fly in your head. named main.py. This will be sys.exit()
series and Full Circle Magazine, Sometimes, it’s easier to sit down important if/when you decide to
and that they are now running on paper and work out that if, for create an Android app from Kivy. Now we work on our build
back to the beginning of the series.
So, those people ARE beginners. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
So, as of part 37, we’ll drop Transposer Ver 0.1
“Beginning” from the series title.
C C#/Db D D#/Eb E F F#/Gb G G#/Ab A A#/Bb B C
____________________________________________________________________
Now to the actual meat of this 1| C#/Db D D#/Eb E F F#/Gb G G#/Ab A A#/Bb B C C#/Db
article... more on Kivy. 2| D D#/Eb E F F#/Gb G G#/Ab A A#/Bb B C C#/Db D
­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

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


HOWTO - BEGINNING PYTHON 36
routine (middle right). This is root =
needed for every Kivy app. GridLayout(orientation='verti import kivy
cal', spacing=10, kivy.require('1.0.8')
cols=1,rows=3) from sys import exit
This looks rather confusing. from kivy.app import App
Unfortunately, the editor doesn’t In this case, the representation from kivy.core.window import Window
always keep spaces correct even in is as follows.... from kivy.uix.button import Button
a mono-spaced font. The idea is from kivy.uix.label import Label
from kivy.uix.anchorlayout import AnchorLayout
that the text1 string is a simple ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ from kivy.uix.scrollview import ScrollView
scale starting with the note “C”. (0) title label from kivy.uix.gridlayout import GridLayout
Each should be centered within 5 ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
(1) main button
spaces. Like the text shown ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
bottom right. (2) scrollview padding and size_hint properties. �� ��� ����� �� ����� ��� ���� ���� ��
­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ The padding is the number of ��� ������� ��� ���������� ����
The text2 string should be the pixels around the item in an x,y
same thing but repeated. We will The scrollview contains multiple reference. Taken directly from the In this case, size_hint is set to
use an offset into the text2 string items – in our case buttons. Next, Kivy documentation size_hint (for none, which defaults to 100% or 1.
to fill in the button text within the we create the label which will be at X which is same as Y) is defined as: This will be more important (and
scrollview widget. the top of our application. convoluted) later on.
����� ����� ���������� �������
Now we create the root object lbl = Label(text='Transposer ����� ��� ������ ��������� �� ��� Now we define our “main”
(which is our main window)
Ver 0.1',
font_size=20,
��������� ����� ������ �������� �� ��� button (next page, top right). This
containing a GridLayout widget. If size_hint=(None,None), �������� ������ ���� ������ ��� is a static reference for the scale.
you remember WAY back when we size=(480,20), ���������� ��� ����� ����� ���
were doing other GUI padding=(10,10)) ����� �� �� ������� �� � ����� ���� �� Again, most of this should be
development for Glade, there was
a grid view widget. Well, the def build(self):
#­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
GridLayout here is pretty much the text1 = " C C#/Db D D#/Eb E F F#/Gb G G#/Ab A A#/Bb B C"
same. In this case, we have a grid text2 = " C C#/Db D D#/Eb E F F#/Gb G G#/Ab A A#/Bb B C C#/Db D
that has one column and three D#/Eb E F F#/Gb G G#/Ab A A#/Bb B C C#/Db"
rows. In each of the cells created in #­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
the grid, we can put other widgets.
Remember, we can’t define which
widget goes where other than in The properties that are set | | | | | | | | | | | |
should be fairly self-explanatory. 12345678901234567890123456789012345678901234567890123456
the order in which we place the C C#/Db E F F#/Gb G G#/Ab A A#/Bb B C
widgets. The only ones that might give you
some trouble would be the
full circle magazine #64 8 �������� �
HOWTO - BEGINNING PYTHON 36
fairly clear. None), size=(600,400))
btn1 = Button(text = " " + text1,size=(680,40),
sv.center = Window.center size_hint=(None, None),
Now we add the widgets to the halign='left',
root object, which is the root.add_widget(sv) font_name='data/fonts/DroidSansMono.ttf',
GridLayout widget. The label (lbl) padding=(20,20))
goes in the first cell, the button Lastly, we add the GridLayout
(btn1) goes in the second. that holds all our buttons
for i in range(0,19):
into the ScrollView, and
#­­­­­­­­­­­­­­­­­­­­­­­­­­­­ if i <= 12:
return the root object to if i < 10:
root.add_widget(lbl)
root.add_widget(btn1) the application. t1 = " " + str(i) + "| "
#­­­­­­­­­­­­­­­­­­­­­­­­­­­­ else:
sv.add_widget(s) t1 = str(i) + "| "
else:
Now comes some harder-to- return root t1 = ''
understand code. We create text2 = ''
another GridLayout object and call btn = Button(text = t1 + text2[(i*5):(i*5)+65],
Finally, we have our “if size=(680, 40),
it “s”. We then bind it to the height __name__” routine. Notice size_hint=(None,None),
of the next widget which, in this that we are setting halign='left',
case, will be the ScrollView, NOT font_name='data/fonts/DroidSansMono.ttf')
ourselves up for the
the buttons. s.add_widget(btn)
possibility of using the #­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
application as an android
s = GridLayout(cols=1,
spacing = 10, size_hint_y = app.
None) The source code can be found
s.bind(minimum_height=s.sette if __name__ in
('__main__','__android__'): on PasteBin at
r('height'))
http://pastebin.com/hsicnyt1
Now (middle right) we create Transpose().run()
Until next time, enjoy and thank
20 buttons, fill in the text
Now you might wonder why I you for putting up with me for
property, and then add it to the
used buttons instead of labels for three years!
GridLayout.
all our textual objects. That’s Greg is the owner of RainyDay
Now we create the ScrollView, because labels in Kivy don’t have Solutions, LLC, a consulting company
any kind of visible border by in Aurora, Colorado, and has been
set its size, and add it to the root programming since 1972. He enjoys
GridLayout. default. We will play with this in
cooking, hiking, music, and spending
the next installment. We will also time with his family. His website is
sv = add an exit button and a little bit www.thedesignatedgeek.net.
ScrollView(size_hint=(None, more.
full circle magazine #64 9 �������� �
HOW-TO
Written by Greg D. Walters
Programming in Python - Part 37

T
his month, we’ll finish up well. I take mine on my tablet than boring gray ones. The next is
the transposer program whenever I go to band practice. I that there are three buttons. #:kivy 1.0
#:import kivy kivy
that we wrote in Kivy. was going to deal with packaging Finally the scrollable labels are
Hopefully, you saved the our project for Android, but some closer to the entire width of the <BoundedLabel>:
code from last time, because we’ll things have changed in the method window. Other than that, it’s canvas.before:
be building upon it. If not, grab the to do that, so we’ll work on that pretty much (visually) the same. Color:
rgb: 0, 0, 1
code from FCM#64. next month. One of the buttons is an “about” Rectangle:
button that will pop up simple pos: self.pos
Let’s start by recapping what The app, as we left it last time, information, but it explains how to size: self.size
we did last month. We created an looked like that shown below left. make a simple popup. One of the
application that allows for a buttons is an exit button. The
guitarist to quickly transpose from When we are done, it should other button will swap the label Let’s get started by creating a
one key to the other. The ultimate look like the screen below right. text to make it easy to transpose .kv file (above right). This is what
goal is to be able to run this app from piano to guitar or guitar to will give us the colored labels. It’s a
not only on your Linux or Windows The first thing you will notice is piano. very simple file.
box, but on an android device as that there are blue labels rather

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


HOWTO - PROGRAMMING IN PYTHON 37
The first two lines are required.
def LoadLabels(w):
They basically say what version of if w == 0:
Kivy to expect. Next we create a tex0 = self.text1
new type of label called tex1 = self.text2
‘BoundedLabel’. The color is set else:
tex0 = self.text3
with RGB values (between 0 and 1, tex1 = self.text4
which can be considered as 100 for i in range(0,22):
percent), and as you can see the if i <= 12:
blue value is set at 100 percent. if i < 10:
t1 = " " + str(i) + "| "
We will also create a rectangle else:
which is the actual label. Save this t1 = str(i) + "| "
as “transpose.kv”. You must use t = tex1
the name of the class that will be else:
t1 = ''
using it. t = ''
l = BoundedLabel(text=t1+t[(i*6):(i*6)+78], size=(780, 35),
Now that you have that size_hint=(None,None),halign='left',
completed, add the following lines font_name='data/fonts/DroidSansMono.ttf')
s.add_widget(l)
just before the transpose class to
the source file from last time:

class BoundedLabel(Label): The LoadLabels routine will give


us the colored labels
pass (BoundedLabel) and the swap
ability. You saw most of this last def Swap(instance):
To make it work, all we need is a if self.whichway == 0:
time. We pass a value to the “w” self.whichway = 1
definition. Before we go any parameter to determine which text btnWhich.text = "Guitar ­­> Piano"
further, add the following line to is being displayed. The btn1.text = " " + self.text3
the import section: l=BoundedLabel line is pretty much s.clear_widgets()
LoadLabels(1)
the same line from last time, with else:
from kivy.uix.popup import
the exception that, this time, we self.whichway = 0
Popup
are using a BoundedLabel widget btnWhich.text = "Piano ­­> Guitar"
instead of a Button widget. The btn1.text = " " + self.text1
This allows us to create the s.clear_widgets()
LoadLabels will mainly be called
popup later on. Now, in the LoadLabels(0)
from the next routine, Swap. Place
Transpose class, just inside the def
this code (shown right) below
build routine, place the code
LoadLabels.
shown above right.
full circle magazine #65 7 �������� �
HOWTO - PROGRAMMING IN PYTHON 37
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|"

You can see that this routine is GridLayout(orientation='verti nsMono.ttf', AnchorLayout widgets for the
pretty self explanatory. We use a cal', spacing=10, three buttons that we will add in
cols=1,rows=3) padding=(20,20))
variable (self.whichway) to later. I named them al0
determine “which way” the labels (AnchorLayout0), al1 and al2. We
to to:
are displaying... from Guitar to also add the code for the About
Piano or Piano to Guitar. root = btn1 = Button(text = " " Popup, and define our buttons
GridLayout(orientation='verti + self.text1,size=(780,20), along with the bind statements.
Be sure to save your work at cal', spacing=6, cols=1, This is shown on the next page, top
this point, since we are going to be rows=4, size_hint=(None, None), left.
row_default_height=40)
making a lot of changes from here halign='left',
on. Find the “s = GridLayout” line
We’ve changed the spacing font_name='data/fonts/DroidSa and change the spacing from 10 to
from 10 to 6 and set the default nsMono.ttf',
Replace the lines defining text1 4. Next, add the following line
row height to 40 pixels. Change the
and text two with the lines shown padding=(20,2), after the s.bind line (right before
text for the label (next line) to
above. the for loop):
“text='Transposer Ver 0.8.0'”. background_color=[0.39,0.07,.
Everything else stays the same on 92,1]) LoadLabels(0)
We set self.whichway to 0 which
this line.
will be our default for the swap
procedure. Then we define four Notice that I’ve changed the This calls the LoadLabels
Now change the button formatting of the first definition routine with our default “which” of
strings instead of the two we had
definition line from... for clarity. The big changes are the 0.
last time. You might notice that
strings text3 and text4 are simple size change from 680,40 to 780,20
btn1 = Button(text = " " +
reversals of text1 and text2. and the background color for the Next, comment out the entire
text1,size=(680,40),
button. Remember, we can change for loop code. This starts with “for i
Now we will tweak the root line size_hint=(None,None), the background color for buttons, in range(0,19):” and ends with
definition. Change it from... not “standard” labels. “s.add_widget(btn)”. We don’t
halign='left',
need this since the LoadLabels
root = font_name='data/fonts/DroidSa Next, we will define three routine does this for us.
full circle magazine #65 8 �������� �
HOWTO - PROGRAMMING IN PYTHON 37
al0 = AnchorLayout() al0.add_widget(btnWhich)
al1 = AnchorLayout() al1.add_widget(btnExit)
al2 = AnchorLayout() al2.add_widget(btnAbout)
popup = Popup(title='About Transposer', bgl = GridLayout(orientation='vertical',
content=Label(text='Written by G.D. Walters'), spacing=6, cols=3,rows=1,
size_hint=(None,None),size=(400,400)) row_default_height=40)
btnWhich = Button(text = "Piano ­­> Guitar", bgl.add_widget(al0)
size=(180,40),size_hint=(None,None)) bgl.add_widget(al1)
btnWhich.bind(on_release=Swap) bgl.add_widget(al2)
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)

Now, save your code and try to shown top right.


run it. You should see a deep
purple button at the top, and our Here we add the three buttons
pretty blue BoundLabels. Plus, you to the AnchorLayout widgets,
will notice that the BoundLabels in create a GridLayout to hold the
the scroll window are closer AnchorLayouts, and then finally
together, which makes it much add the AnchorLayouts to the
documentation on this. Be sure to
easier to read. GridLayout.
Now our code is written. You follow the documentation
can find the full code at carefully.
We are almost through with our Go back just below the “def
Swap” routine and add the http://pastebin.com/GftmjENs
code, but we still have a few things See you next month.
to do. After the “sv = ScrollView” following...
Next, we need to create our
line add the following line... android package... but that will
def ShowAbout(instance):
have to wait for next time.
sv.size = (720, 320) popup.open() Greg is the owner of RainyDay
Solutions, LLC, a consulting company
If you want to get set up and try
This sets the size of the That’s it. Save and run the code. in Aurora, Colorado, and has been
packaging for Android before next programming since 1972. He enjoys
ScrollView widget to 720 by 320 – If you click on the About button, month, you should go to cooking, hiking, music, and spending
which makes it wider within the you will see the simple popup. Just time with his family. His website is
http://kivy.org/docs/guide/packagi
root window. Now, before the click anywhere outside of the www.thedesignatedgeek.net.
ng-android.html for the
“return root” line, add the code popup to make it go away.
full circle magazine #65 9 �������� �
HOW-TO
Written by Greg Walters
Programming In Python: Pt 38

A
s I promised in part 37, ./build.py --dir <path to your app>
we will take the --name "<title>"
transposer app that we --package <org.of.your.app>
--version <human version>
created, and create an --icon <path to an icon to use>
APK to install it on your android --orientation <landscape|portrait>
device. --permission <android permission like VIBRATE> (multiple allowed)
<debug|release> <installd|installr|...>
Before we get started, let’s
make sure we have everything will need to download the python- taken directly from the Kivy this is the name of the application
ready. First thing we need is the for-android software. Open a documentation. that will show up in the apps
two files we created last time in a terminal window and type the drawer.
folder that you can easily access. following... For our use, we will use the --version 1.0.0 - the version of our
Let’s call it “transposer”. Create it following command (the “\” is a application
in your home directory. Next, copy git clone
line continuation character): debug - this is the level of release
the two files (transpose.kv and git://github.com/kivy/python-
for-android (debug or release)
transpose.py) into that folder. Now ./build.py --dir ~/transposer
rename transpose.py to main.py. --package
Once you execute this,
This will download and set up org.RainyDay.transposer \
This part is important. assuming that everything worked
the software that we need to --name "RainyDay Transposer"
continue. Now, in a terminal --version 1.0.0 debug as expected, you should have a
Next, we need to reference the number of files in the /bin folder.
window, change your directory to
kivy packaging instructions in a Let’s look at the pieces of the The one you are looking for is
the python-for-
web browser. The link is command... titled “RainyDayTransposer-1.0.0-
android/dist/default folder.
http://kivy.org/docs/guide/packagi debug.apk”. You can copy this to
ng-android.html. We will be using ./build.py - this is the application your android device using your
Now you will find a file called
this for the next steps, but not --dir ~/transposer - this is the favorite file manager app, and
build.py. This is what will do all the
exactly as the Kivy people directory where our application install it just like any other
work for us. Now comes the magic.
intended. You should have the code lives. application from the various app
android SDK from our earlier --package stores.
The build.py program will take
lesson. Ideally, you will go through org.RainyDay.transposer - This is
various command-line arguments
and get all the software that is the name of the package That’s all I have time for this
and create the APK for you. Shown
listed there, but for our purposes, --name “RainyDay Transposer” - month.
above is the syntax for build.py
you can just follow along here. You
full circle magazine #67 8 �������� �

You might also like