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

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

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

However there aresome restrictions when using an emulator, compared to using an S60phone. For example, you cannot send and receive SMS messages or takea photo with an emulator. Check Appendix D for instructions on how toset up the emulator.2.6 SummaryJumping head first into hands-on action, we showed you in this chapterhow to write your first script with PyS60 and how to run it on your S60mobile phone. We covered the basic steps to do this:1.Download the installation files from the Internet.2.Install the downloaded .SIS files to your phone.3.Write a Python script on your computer.4.Upload your Python script to the phone.5.Test your script on the phone.In Section 2.3, we programmed our first PyS60 application with threelines of code. We hope this example got you excited to discover allthe great things you can do with PyS60.

By continuing with a practicalhands-on approach, we guide you through the next chapter, helping youto unfold your creativity and enabling you to program applications basedon your own ideas.If you feel really bold and adventurous now, you can see an alternativeapproach for updating PyS60 scripts on the phone over a networkconnection in Section 10.3.3. For some developers, this might be themost productive way to use PyS60. If you want to see even more niftytricks that PyS60 can do, Appendix B tells you how to use the PyS60interpreter remotely on your PC over Bluetooth.3Graphical User Interface BasicsThe native graphical user interface elements are some of the easiest tolearn of the features that Python for S60 offers. We cover them here at thebeginning of the book, to give you a smooth start in learning PyS60.We explain the graphical user interface (UI) elements using smallexercises.

Each exercise includes instructions, screenshots and detailedcode descriptions. These exercises should help you in understanding andrunning the examples presented in the subsequent chapters. We alsocover some Python language lessons, which will help you to get to knowthe Python programming language by heart, through learning by doing.In Example 1 (see Chapter 2), we introduced two native graphical userinterface elements: the text input field (a single-field dialog) and thepopup note. Here we want to show a whole range of them:•note – popup notes•query – single-field input dialog•multi-query – two-field text input dialog•popup menu – simple menu•selection list – simple list with find pane•multi-selection list – list to make multiple selectionsIn the following paragraphs, we look at these elements in detail andexplain how you can use them in your own programs.3.1 Using ModulesThe native UI elements that PyS60 offers are accessible through a modulecalled appuifw (which stands for application user interface framework).32GRAPHICAL USER INTERFACE BASICSIt is an interface to the S60 UI application framework that takes care ofall UI functionalities on the S60 platform.

But before we go on, let’s learnwhat a ‘module’ is in Python, in the language lesson.Python Language Lesson: moduleA module is a file that contains a collection of related functions and datagrouped together. PyS60 comes with a rich set of modules, for examplemessaging to handle SMS functionalities, camera for taking photos,and appuifw, which provides ready-to-use UI elements.

The modules’contents are described in detail in the Python Library Reference andPython for S60 API documentation. We also learn about many of themin this book.To use a module in your code, it must be imported at the beginningof the script, for example:import appuifwTo address a function contained in a module, we first write themodule name, a dot and then the function name:appuifw.query(label, type)Here, appuifw is the module name and query is the function wewant to use.You may import many modules using a single import statement:import appuifw, e32This imports two modules: appuifw and e32.As you might remember from our Example 1 (Chapter 2), we used thefunctions query() and note(), which belong to the appuifw module.These functions generate UI elements, dialogs, that are displayed on thescreen when the PyS60 interpreter executes the script.

They becomevisible on the phone screen as soon as the corresponding Python functionis called.3.2 Native UI Elements – Dialogs, Menus and SelectionListsLet’s now look in detail at some of the native UI elements or dialogs thatPyS60 offers.NATIVE UI ELEMENTS – DIALOGS, MENUS AND SELECTION LISTS333.2.1 Single-Field Dialog: querySyntax: query(label, type[, initial value ])Example code:appuifw.query(u"Type a word:", "text", u"Foo")This function shows a single-field dialog. The dialog can include someinstruction text that is passed as a string (by putting the u in front of thestring) to the parameter, label.

The type of the dialog is defined bythe parameter, type. The value of type can be any of the followingstrings: "text", "number", "date", "time", "code", "query" or"float" (see Figure 3.1).Figure 3.1(a)(b)(c)(d)(e)(f)Types of single-field dialog: (a) text, (b) number, (c) date, (d) time, (e) code and (f) query34GRAPHICAL USER INTERFACE BASICSAn initial value can be included, so the dialog shows a default inputvalue when it appears on the phone screen. This is done simply by addingthe initial value as an input parameter to the function, for example:appuifw.query(u"Type a word:", "text", u"Foo")The return value of the appuifw.query() function depends on thetype parameter:•For text fields (types of ‘text’ and ‘code’), the return value is a Unicodestring.•For number fields, it is an integer.•For date fields, it is the number of seconds since the epoch (0:00 on1 January 1970, UTC) rounded down to the nearest local midnight.ExerciseTo see how the various single-input dialogs appear on your phone, typethe lines of code in Example 2 into your text editor and save the file witha name ending .py.

Transfer the .py file to your phone or to the emulatoras described in Chapter 2. Start the PyS60 interpreter on the phone andselect ‘Options’. Select ‘Run script’, choose your script from the list, select‘OK’ and see what happens.You should see all the single-input dialogs as in Figure 3.1 appear onyour phone’s screen one by one. Each dialog will wait for you to typesomething in and select ‘OK’.Example 2: Various dialogsIf you want, change the instruction text (the label parameter) of thequery function.

As you can see, we need to import the appuifw moduleat the beginning of the script to make this work.import appuifwappuifw.query(u"Type aappuifw.query(u"Type aappuifw.query(u"Type aappuifw.query(u"Type aappuifw.query(u"Type aappuifw.query(u"Do youword:", "text")number:", "number")date:", "date")time:", "time")password:", "code")like PyS60", "query")Since Symbian OS and the S60 platform are used all over the world,they need to be able to show text written in various languages and writingsystems.

Unicode provides a consistent way to encode text written inany writing system. In order to be globally compatible, all text-relatedNATIVE UI ELEMENTS – DIALOGS, MENUS AND SELECTION LISTS35functionalities in S60 and Symbian OS accept only Unicode strings. InPython, the ‘u’ character in front of a string denotes that the text is writtenin Unicode. If you see strange boxes on the screen instead of characters,you have probably forgotten to put ‘u’ in front of the corresponding text.We talk more about Unicode conversions in Section 6.2.3.2.2Note Dialog: noteSyntax: note(text[, type[, global ] ])Example code:appuifw.note(u"upload done", "conf")This function displays a note dialog (a popup note) on your phone withuser-specified text.

In the example, it displays the words ‘upload done’.This is achieved by passing the Unicode string ‘upload done’ as the inputparameter text.There are three possibilities for type : "info", "error" and "conf"(see Figure 3.2). Each type shows a different symbol inside the popup notedialog: ‘info’ shows a green exclamation mark after the text and ‘error’shows a red exclamation mark. The default value for type is "info",which is automatically used if type is not set.(a)Figure 3.2(b)(c)Types of note dialog: (a) information, (b) error, (c) confirmationExerciseTo see how the popup notes appear on your phone, type in the linesof code shown in Example 3 and run your script on your phone or theemulator to see what happens.36GRAPHICAL USER INTERFACE BASICSYou should see all the different popup notes appear on your phonescreen one by one.Example 3: Various notesNote again that we need to import the appuifw module at the beginningof the script in order make this work.import appuifwappuifw.note(u"Hello")appuifw.note(u"File not found", "error")appuifw.note(u"Upload done", "conf")Python Language Lesson: variableA variable is a name that refers to a value.

In Python you do not haveto declare variables, that is, you do not have to specify in advance thetype, such as integer, string, and so on. Variables are implicitly typed,meaning that the type of a variable is the type of the value it refers to.If your variable holds the integer 5 but you need the string ‘5’, youhave to use the str() function to convert the integer to a string.

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

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

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

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