Главная » Просмотр файлов » 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), страница 11

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

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

A colonends the function header.The indented lines below the function header form the functionbody, which is executed line by line when the function is called. InPython, indentation makes a difference, so make sure that the linesare aligned correctly in the function body. Function bodies follow thesame indentation rules as if clauses and loops. The function body maycontain a return statement followed by a value which is returned tothe calling line. The return statement is optional.A function is called with the function name followed by the inputvalues in parentheses:z = 3new sum = add values(z, 5)print "Their sum is", new sumIf no input values are given, there is nothing between the parentheses.The return value may be assigned to a variable, for examplenew sum = add values(z, 5), or the function call may be includedin a more complex expression.

For example, the code of the last linein the example above could have read:print "Their sum is", add values(z, 5)In this case, you would not need the new sum variable in theexample above. As you might guess, the example produces this output:Values are 3 5Their sum is 852APPLICATION BUILDING AND SMS INBOXPython’s slogan is ‘Batteries included’. This refers to the fact thatPython comes with a comprehensive library of pre-made functions whichmake many complex tasks practically effortless.4.2 Application StructureMany S60 applications share the same user interface layout. Take alook at Figure 4.1 or almost any application on your S60 mobile phone,including the PyS60 interpreter and you will notice the same structure inthe user interface.(a)(b)Figure 4.1 A typical user interface (a) structure and (b) screenshot based on the structureFigure 4.1(a) shows the structure of the S60 user interface.

To see howthe diagram maps to reality, compare it to Figure 4.1(b), which showsa typical user interface that is built using the S60 UI framework. In thefollowing description, text in parentheses refers to text in the screenshot.At the top of the screen, you see the application title (Tabs). Below thetitle, you may see a row of navigation tabs (One and Two). The large areain the middle is the application body which may be used by a number ofdifferent UI elements (the list: red, green, blue, brown). Various dialogs,such as popup notes, may appear on the application body, as we saw inChapter 3.At the bottom, you see two items that are activated by two dedicatedkeys, the left and right softkeys, on your mobile phone keyboard.

If noAPPLICATION STRUCTURE53dialog is active, the left softkey activates the application menu (Options)and the right softkey quits the running application (Exit). If a dialogis shown, the left softkey corresponds to Accept and the right one toCancel.In PyS60, you can access the UI elements through a special appobject that is part of the appuifw module.

We talk more about objectsin Section 4.2. Modifying the UI elements is easy: each of the elements(title, body, menu and exit key handler) is a special variableinside the appuifw.app object and you can assign values to them asyou can to any other variable. Just remember to use the full name, forinstance appuifw.app.title. Whenever you change any of thesevariables, the corresponding UI element changes accordingly.The first application is a minimalist application that uses the UI framework provided by the appuifw module.

It does not do anything usefulbut it illustrates the minimum requirements for a working application. Itruns until the user chooses to quit the application, as opposed to previousexamples, which executed deterministically from the beginning to theend. Figure 4.2 shows it in action.Figure 4.2 First applicationThis section includes two language lessons that are related to application building, about callback functions and objects. Do not worry if youcannot grasp them at once. They will become clear with the many moreexamples that follow.54APPLICATION BUILDING AND SMS INBOXExample 11: First applicationimport appuifw, e32def quit():print "Exit key pressed!"app_lock.signal()appuifw.app.exit_key_handler = quitappuifw.app.title = u"First App!"appuifw.note(u"Application is now running")app_lock = e32.Ao_lock()app_lock.wait()print "Application exits"Besides importing the familiar appuifw module, we also need amodule named e32.

This module offers many useful low-level utilityobjects and functions related to Symbian OS functionalities. Here weneed the object e32.Ao lock().We define a new function, quit(), that takes care of shutting downthe application when the user presses the Exit key. Since we could havea number of functions to perform various tasks, we need to tell Pythonwhich function is dedicated to handling the Exit events.This is done by assigning the function name (not its value) to thespecial appuifw.app.exit key handler variable. When the userpresses the Exit key, the function that this variable refers to is called bythe UI framework. In many situations, Python expects you to provide afunction name that is used to call the corresponding function when someevent has occurred. Functions of this kind are called callback functions.The language lesson about callback functions clarifies the concept.Python Language Lesson: callback functionA callback function is an ordinary function, defined similarly to anyother function, but it is used for a specific purpose.

There is no technicaldifference between ordinary functions and callback functions. Thedistinction is made to clarify discussion.Typically, a callback function is called by a function in the PyS60library to respond to a specific event – such as when the user haschosen a menu item or decides to quit the application. In contrast,ordinary functions are called in your application code to handleapplication-specific tasks.

However, in some cases a callback functionmay be called by your application explicitly.Associating a function with an event is often called binding. SomePyS60 objects, such as Canvas and Inbox, include a function calledbind() that is used to bind a callback function to some event relatedto the object.APPLICATION STRUCTURE55Whenever the PyS60 API documentation or this book asks you toprovide a callback function, do not add parentheses after the functionname since the function is only called after the event occurs.

If youare familiar with C or C++, you might notice that this is similar to howfunction pointers are passed around in these languages.In Example 11, we then assign the application name to the title variableappuifw.app.title. This string shows at the top of the screen whenthe application is running.As we discussed at the beginning of this chapter, the PyS60 exampleswe have seen so far are executed line by line and they exit when the lastline has been executed. However, Example 11 should not exit until theuser decides to do so. Therefore, our application should not drop out afterthe last line has been executed, but instead should wait for user action.This is accomplished with an object called Ao lock that is part ofmodule e32.

The object includes a function called wait() that puts theapplication into a waiting mode until the lock is explicitly released with thesignal() function. The signal() function must be called when youwant to terminate the application, so we call it inside the quit function.To see why it’s important to have the lock at the end of the applicationcode, omit the line, app lock.wait(), from your code and run theapplication. A dialog pops up but the application does not go into a waitstate; it finishes instantly.When you run Example 11, you should see the ‘First App!’ title at thetop of the screen (as in Figure 4.2) and a dialog popping up.

Nothing elsehappens until you press the Exit key (the right softkey), which shuts downthe application. After this, you should see the text ‘Exit key pressed!’ and‘Application exits’ messages in the PyS60 console on the phone screen.It might be difficult to notice that the application is running at all. Thisis because the PyS60 interpreter is built using exactly the same applicationframework, so it looks the same as any other PyS60 application.Python Language Lesson: objectObjects hold together variables and the functions that manipulate them.In many cases, functions and variables are so closely related to eachother that they would be meaningless if they were handled separately.Objects are especially useful in large, complicated applications whichwould be practically incomprehensible if they were not divided intosmaller units.Python does much of this work for you, so you can code happilywith Python’s ready-made objects.

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

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

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

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