Главная » Просмотр файлов » Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007

Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889), страница 9

Файл №779889 Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (Symbian Books) 9 страницаWiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889) страница 92018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 9)

Thetype of a value does not change automatically.The first time you use a variable, assignment is done with the equalssign ‘=’. It creates a new variable and gives the variable a value, forexample:data = 5mynewlist = "Symbian"The special value None denotes a missing value. You can re-use thesame variable freely throughout a program.In some examples, we use capital letters for variable names. This isa common way in Python to denote variables whose values must notchange (that is, they are constants), as a convenience to developers.The interpreter itself does not care if they are constant.3.2.3Multi-Query Dialog: multi querySyntax: multi query(label1, label2)Example code:appuifw.multi_query(u"First name:", u"Last name:")This function displays a two-field text input dialog.

The input parameters label1 and label2 can be pre-defined by inserting Unicode strings.NATIVE UI ELEMENTS – DIALOGS, MENUS AND SELECTION LISTS37The multi_query() function returns the values that the user inputs.The values of the upper and lower input fields are jointly returned as atuple. In Python, a tuple is a comma-separated list of values, for example(data1, data2). We learn more about handling tuples in Chapter 4. Thisfunction, as with other dialogs, returns the empty value None if the usercancels the dialog.ExerciseTo see how the multi-query dialog (Figure 3.3) appears on your phone,create a script (shown as Example 4) that displays a multi-query dialogthat asks you to type your first name into the upper field and your lastname into the lower field.

After typing your names and pressing the ‘OK’button, a popup note should appear, displaying your full name.Figure 3.3A multi-query dialogExample 4: Multi-query dialogimport appuifwnames = appuifw.multi_query(u"First name:", u" Last name:")if names:first, last = namesappuifw.note(u"Your full name is: " + first + " " + last)else:appuifw.note(u"Cancel!")First we import the module appuifw.

Then we pass two Unicode stringsto the multi query() function. The function returns the user’s inputfrom the fields into a variable called names as a tuple.38GRAPHICAL USER INTERFACE BASICSIn the third line of code we use an if statement. If the variable namesholds some content, that is, the variable names is not None, then thecondition is true and we read the tuple’s entries and hand them overto the variables first and last.

The if statement is described in thelanguage lesson more thoroughly.Next we create an informative popup note. The text that we pass tothe note function consists of three parts: the string u"Your full nameis: " and the stored values in the first and last variables combinedwith a ‘+’ sign and with " " as a space between them.Python Language Lesson: if statementAn if statement is needed to make decisions based on variable values:if x > 0:appuifw.note(u"x is positive!")else:appuifw.note(u"x is negative or zero.")The Boolean expression after the word ‘ if’ is called the condition.If the condition is true (in this case, if the value of the variablex is bigger than 0), then the indented statement in the next line(here, appuifw.note(u"x is positive!") ) is executed. If thecondition is false, the statement in the else branch is executed (here,appuifw.note(u"x is negative or zero.") ).

Note that youcan reverse the outcome of the condition, by putting the not keywordin front of the condition.The most important comparison operators are ==, !=, < and >, forequality, inequality, less than and greater than. Note that if you wantto test whether a variable is not false, zero, None or an empty string orlist, you can use the following shorthand:if x:appuifw.note(u"x is not empty")You can test many conditions in sequence:if x > 0:appuifw.note(u"x is positive!")elif x == 0:appuifw.note(u"x is zero.")else:appuifw.note(u"x is negative.")NATIVE UI ELEMENTS – DIALOGS, MENUS AND SELECTION LISTS39Here, elif stands for ‘else if’.

You can have multiple elif statements after each other. They are evaluated in sequence until one ofthe conditions evaluates to true.The indented statements that follow a condition are called a block.The first unindented statement marks the end of the block. You mustindent the statements in the block (see Section 2.4), otherwise thePython interpreter does not know where the block begins and ends.In other programming languages, for example, C++, this is solvedby starting and ending a block with brackets.

Having no brackets inPython makes the code easier and clearer to read.Python Language Lesson: listA list is an ordered set of values. The values that make up a list arecalled its elements or items. The items can be of any type, such asstrings or integers. Items of the list do not have to be of the same type,so you can have a list that contains both strings and integers.There are several ways to create a new list. The simplest is to enclosethe elements in square brackets:mylist = [u"Symbian", u"PyS60", u"MobileArt"]Each item in the list can be accessed by its index in square bracketsafter the list name: in the example, mylist[0] refers to the value"Symbian" and mylist[2] to "MobileArt". We can also assignvalues to specific items in the list:mylist[1] = "Python"You can access parts of the list easily with the [start:end]notation for the index – this is called slicing the list.

For instance,mylist[1:2] returns a new list that includes the items ["Pys60","MobileArt"]. Optionally, you can leave out either the start indexor the end index. For instance, mylist[:1] returns a new list withthe items ["Symbian", "PyS60"].To add another element to the end of the list, use the append()function. For instance, the following linemylist.append(u"Fun")would change the list to contain the following items: ["Symbian","PyS60", "MobileArt", "Fun"].40GRAPHICAL USER INTERFACE BASICS3.2.4 Popup Menu: popup menuSyntax: popup menu(list[, label ])Example code:appuifw.popup menu(choices, u"Select:")The popup menu() function displays a list of items in a popup dialog.You need to give a list of Unicode strings in the parameter list.

Youcan also define a label which is the text that appears at the top of the list.This function returns the index of the chosen item in the list. If the usercancels the dialog by pressing Back, None is returned.ExerciseCreate a script (see Example 5) that displays a popup menu with threeentries, such as the one in Figure 3.4.

After selecting any of the choicesand pressing ‘OK’, you should see a note appear with different textdepending on which selection you made. Use the phone’s up and downkeys to make the selection from the menu.Figure 3.4 A popup menuExample 5: Popup menuimport appuifwchoices = [u"Symbian", u"PyS60", u"MobileArt"]index = appuifw.popup_menu(choices, u"Select:")if index == 0:appuifw.note(u"Symbian, aha")elif index == 1:appuifw.note(u"PyS60 - yeah")elif index == 2:appuifw.note(u"I love MobileArt")NATIVE UI ELEMENTS – DIALOGS, MENUS AND SELECTION LISTS41First we import the module appuifw.

In the next line, we create alist with three elements [u"Symbian", u"PyS60", u"MobileArt"].Each element represents an entry in the menu. The list is assigned to thevariable choices.In the next line, we use the popup menu() function and pass thevariable choices as the first parameter to the function. We also pass aUnicode string u"Select:" as the second parameter to the function.When our script is executed, the function returns an index that refersto one of the elements of our list – depending on the user’s selection. Thereturned index – a number – is stored in a variable that we have namedindex.Now, we need some code that displays a note dialog with differentcontent depending on the user’s selection. This is done using the ifstatement, simply by checking the returned list index and comparing itto all possible options: 0, 1, 2.

If the user cancels the dialog, none of theconditions is true and no dialog is shown.3.2.5Selection List: selection listSyntax: appuifw.selection list(choices, search field)Example code:appuifw.selection_list(colors, 1)The selection list() function executes a dialog that allows theuser to select a list item. It works similarly to the popup menu() functionexcept that it has no label on the top.

Instead, it has an option to displaya built-in search field (a find pane) at the bottom (see Figure 3.5).Compared to the popup menu, the selection list is more suitablefor presenting long lists, especially because of the search field that letsyou find items in the list character by character. Setting the parametersearch field to 1 enables the find pane. It is disabled by default.

Ifthe find pane is enabled, it appears only after you press a letter key.The selection list() function returns the index of the chosenitem or None if the selection is cancelled by the user.ExerciseTo see how the selection list appears on your phone, create a script(see Example 6) that displays a selection list() dialog with fourentries – ‘red’, ‘green’ ‘blue’ and ‘brown’, as in Figure 3.5.When running the script, type the letter ‘b’. The find pane shouldappear at the bottom of the list and the entries ‘blue’ and ‘brown’ shouldappear. Select ‘blue’ and press the OK button. Text should appear, saying42GRAPHICAL USER INTERFACE BASICSFigure 3.5Selection list‘blue is correct!’.

If you select something else, for instance red, a textshould appear stating ‘Bzz! red is not correct’.Example 6: Selection listimport appuifwcolors = [u"red", u"green", u"blue", u"brown"]index = appuifw.selection_list(colors, 1)if index == 2:print "blue is correct!"elif index != None:print "Bzz! " + colors[index] + " is not correct"We create a list with four colors that are specified as Unicode strings.Each element represents an entry in our selection list dialog. The list isassigned to the variable colors.In the next line, we use the selection list() function and passcolors to it.

We also enable the find pane by setting 1 as the secondparameter. When our script is executed – and the user makes a selection – this function returns an index that refers to an element inside ourlist of colors.Now, we need some code that determines whether the user hasselected the third item in the list or not. We compare the value of theindex variable with the correct index, 2. If the condition is true, weprint the text ‘blue is correct!’ to the screen. Otherwise, if the user did notcancel the dialog, our script enters the elif block.NATIVE UI ELEMENTS – DIALOGS, MENUS AND SELECTION LISTS43There, we combine another string to be printed out on the screen.We pick the chosen color name from the colors list using the returnedindex in the variable index and put it in the middle of the string to beprinted out.In Python, you can print out almost any value, including lists andtuples, and see the contents on the screen in a human-readable format.This makes the print statement especially useful for debugging.

If youwant to know more about debugging at this point, you should lookat Appendix B C where we explain the easiest ways to debug PyS60programs.Python Language Lesson: print statementThe print statement causes the PyS60 interpreter to display a value onthe screen:print "hello"There is no need to indicate that it is a Unicode string because it usesonly the resources of the Python interpreter and no native resourcesfrom the S60 platform.3.2.6 Multi-Selection List: multi selection listSyntax: multi selection list(choices[, style,search field ])Example code:appuifw.multi_selection_list(choices, 'checkbox', 1)The multi selection list() function shows a dialog that allowsthe user to select multiple list items.

The function returns a tuple ofindices of the chosen items, or an empty tuple if the user cancels theselection.In Example 7, the parameter choices is a list of Unicode strings andstyle is an optional string with the default value "checkbox". Thisdialog shows a check box to the left of each item in the list. You canbrowse the list with the navigation keys on the mobile phone keyboardand select items by pressing the Select key (see Figure 3.6).The search field parameter is 0 (disabled) by default and it isoptional. Setting it to 1 shows a find pane that helps the user search foritems in long lists. If enabled, the find pane is always visible with thelist.44GRAPHICAL USER INTERFACE BASICSFigure 3.6 Multi-selection listExample 7: Multi-selection listimport appuifwcolors = [u"red", u"green", u"blue", u"orange"]selections = appuifw.multi_selection_list(colors,'checkbox',1)print selectionsPython Language Lesson: for loopThe for loop goes through the items of a list.

Характеристики

Тип файла
PDF-файл
Размер
3,61 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6447
Авторов
на СтудИзбе
306
Средний доход
с одного платного файла
Обучение Подробнее