copy intermediate python 3 - itcourseware€¦ · using predefned dialogs.....9-21 creating custom...

63
I NTERMEDIATE PYTHON 3.X EVALUATION COPY Unauthorized Reproduction or Distribution Prohibited

Upload: lamdieu

Post on 19-Apr-2018

215 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

INTERMEDIATE

PYTHON 3.X

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 2: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

Intermediate Python 3.x

Table of Contents

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 3: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 4: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 TOCAbout this Course

Chapter 1 – Python Refresher

Variables......................................................................................................................1-1

Basic Python data types..............................................................................................1-2

Sequences....................................................................................................................1-3

Mapping types.............................................................................................................1-4

Program structure........................................................................................................1-5

Files and console I/O...................................................................................................1-7

Conditionals................................................................................................................1-8

Loops...........................................................................................................................1-9

Builtins......................................................................................................................1-11

Chapter 2 – OS Services

Chapter 2 Objectives...................................................................................................2-1

The os module.............................................................................................................2-2

Paths, directories, and flenames.................................................................................2-6

Environment variables..............................................................................................2-10

Launching external programs....................................................................................2-12

Walking directory trees.............................................................................................2-15

The datetime module.................................................................................................2-17

The time module.......................................................................................................2-19

The calendar module.................................................................................................2-22

Chapter 3 – Pythonic Programming

Chapter 3 Objectives...................................................................................................3-1

Pythonic programming................................................................................................3-2

The Zen of Python.......................................................................................................3-3

Common Python idioms.............................................................................................3-4

Unpacking function arguments...................................................................................3-5

Lambda functions........................................................................................................3-6

List comprehensions...................................................................................................3-7

Iterables.......................................................................................................................3-8

Generator expressions.................................................................................................3-9

Writing generators.....................................................................................................3-11

String tricks...............................................................................................................3-12

String formatting.......................................................................................................3-13

Intermediate Python 3.x TOC-1© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 5: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

TOC rev. 2.0

Chapter 4 – Modules

Chapter 4 Objectives...................................................................................................4-1

Modules.......................................................................................................................4-2

Using import..............................................................................................................4-4

Module search path.....................................................................................................4-5

Namespaces.................................................................................................................4-6

Executing modules as scripts......................................................................................4-7

Packages......................................................................................................................4-9

Confguring import with __init__.py........................................................................4-11

Name resolution (AKA Scope).................................................................................4-13

Python style...............................................................................................................4-15

Chapter 5 – Classes

Chapter 5 Objectives...................................................................................................5-1

Defning classes...........................................................................................................5-2

Instance objects...........................................................................................................5-3

Instance attributes.......................................................................................................5-4

Instance Methods........................................................................................................5-5

__init__.......................................................................................................................5-6

Properties....................................................................................................................5-7

Class data....................................................................................................................5-9

Class methods...........................................................................................................5-10

Inheritance.................................................................................................................5-11

Multiple inheritance..................................................................................................5-13

Using super().............................................................................................................5-14

Special methods........................................................................................................5-15

Class-private variables..............................................................................................5-21

Static methods...........................................................................................................5-22

Chapter 6 – Metaprogramming

Chapter 6 Objectives...................................................................................................6-1

Metaprogramming.......................................................................................................6-2

globals() and locals()...................................................................................................6-3

Working with attributes...............................................................................................6-4

The inspect module.....................................................................................................6-6

Decorator functions.....................................................................................................6-8

Decorator classes.......................................................................................................6-10

Decorator parameters................................................................................................6-11

Creating classes at runtime.......................................................................................6-12

Monkey patching.......................................................................................................6-13

TOC-2 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 6: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 TOCChapter 7: Developer Tools

Chapter 7 Objectives...................................................................................................7-1

Program development.................................................................................................7-2

Comments...................................................................................................................7-3

pylint...........................................................................................................................7-4

Customizing pylint.....................................................................................................7-5

Using pyreverse.........................................................................................................7-6

The unittest module...................................................................................................7-7

Fixtures........................................................................................................................7-9

Skipping tests............................................................................................................7-11

Making a suite of tests..............................................................................................7-12

Automated test discovery..........................................................................................7-14

Using nose................................................................................................................7-15

The Python debugger................................................................................................7-16

Starting debug mode.................................................................................................7-17

Stepping through a program......................................................................................7-18

Setting breakpoints....................................................................................................7-19

Profling.....................................................................................................................7-20

Benchmarking...........................................................................................................7-21

Chapter 8 – Database access

Chapter 8 Objectives...................................................................................................8-1

The DB API.................................................................................................................8-2

Available Interfaces.....................................................................................................8-3

Connecting to a server.................................................................................................8-4

connect() examples.....................................................................................................8-5

Creating a cursor.........................................................................................................8-6

Executing a statement.................................................................................................8-7

Fetching data...............................................................................................................8-8

Parameterized statements..........................................................................................8-10

Dictionary cursors.....................................................................................................8-12

Metadata....................................................................................................................8-15

Transactions..............................................................................................................8-17

Object-relational mappers.........................................................................................8-18

Intermediate Python 3.x TOC-3© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 7: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

TOC rev. 2.0

Chapter 9: PyQt4

Chapter 9 Objectives...................................................................................................9-1

What is PyQt4?...........................................................................................................9-2

Event Driven Applications..........................................................................................9-3

GUI Application Flow Chart.......................................................................................9-4

External Anatomy of a PyQt4 Application.................................................................9-5

Internal Anatomy of a PyQt4 Application...................................................................9-6

Using designer............................................................................................................9-7

Anatomy of a designer-based application...................................................................9-9

Naming Conventions.................................................................................................9-10

Common Widgets......................................................................................................9-11

Layouts......................................................................................................................9-13

Selectable Buttons.....................................................................................................9-14

Actions and events....................................................................................................9-15

Menu bar...................................................................................................................9-18

Status bar...................................................................................................................9-19

Using predefned dialogs...........................................................................................9-21

Creating custom dialogs............................................................................................9-23

Tabs...........................................................................................................................9-25

Niceties......................................................................................................................9-27

Working with images................................................................................................9-28

Complete example.....................................................................................................9-30

Chapter 10 – Network Programming

Chapter 10 Objectives...............................................................................................10-1

Sockets......................................................................................................................10-2

Socket options...........................................................................................................10-3

Client concepts..........................................................................................................10-4

Server concepts.........................................................................................................10-5

Application protocols................................................................................................10-6

Forking servers..........................................................................................................10-7

Grabbing HTML from the Web................................................................................10-8

Consuming Web services........................................................................................10-10

Web data the easier way..........................................................................................10-12

Sending email..........................................................................................................10-14

Binary data..............................................................................................................10-16

The struct module..................................................................................................10-17

TOC-4 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 8: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 TOCChapter 11 – Multiprogramming

Chapter 11 Objectives...............................................................................................11-1

Multiprogramming....................................................................................................11-2

What are threads?......................................................................................................11-3

The python thread manager.......................................................................................11-4

The threading module..............................................................................................11-5

Threads for the impatient..........................................................................................11-6

Creating a thread class..............................................................................................11-7

Variables sharing.....................................................................................................11-10

Using queues...........................................................................................................11-12

Debugging threaded programs................................................................................11-15

The multiprocessing module...................................................................................11-16

Alternatives to multiprogramming..........................................................................11-19

Chapter 12 – System Administration and Scripting

Chapter 12 Objectives...............................................................................................12-1

The subprocess module.............................................................................................12-2

Subprocess convenience functions............................................................................12-4

Using the sh module..................................................................................................12-7

Remote Access........................................................................................................12-10

Permissions.............................................................................................................12-13

Saving Information.................................................................................................12-15

Creating a useful command line script....................................................................12-16

Creating flters.........................................................................................................12-17

Parsing the command line.......................................................................................12-20

Simple logging........................................................................................................12-24

Logging levels.........................................................................................................12-25

Formatting log entries.............................................................................................12-27

Logging to other destinations..................................................................................12-29

Intermediate Python 3.x TOC-5© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 9: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

TOC rev. 2.0

Chapter 13 – XML and JSON

Chapter 13 Objectives...............................................................................................13-1

About XML...............................................................................................................13-2

Normal approaches to XML.....................................................................................13-3

Which module to use?...............................................................................................13-4

Getting started with ElementTree.............................................................................13-5

How ElementTree works...........................................................................................13-6

Creating a new XML Document...............................................................................13-8

Parsing an XML Document....................................................................................13-10

Navigating the XML Document..............................................................................13-11

Using XPath............................................................................................................13-13

Advanced XPath.....................................................................................................13-15

About JSON............................................................................................................13-17

Reading JSON.........................................................................................................13-18

Writing JSON..........................................................................................................13-19

Chapter 14 – Extending Python with C

Chapter 14 Objectives...............................................................................................14-1

Why extend Python?.................................................................................................14-2

Ways to extend Python with C..................................................................................14-3

Hand-coded C...........................................................................................................14-4

Overview...................................................................................................................14-5

The C program..........................................................................................................14-6

Methods.....................................................................................................................14-7

The method table.......................................................................................................14-8

The init function........................................................................................................14-9

Handling errors.......................................................................................................14-10

Custom exception objects.......................................................................................14-11

Putting it all together...............................................................................................14-13

Using SWIG............................................................................................................14-17

The interface fle.....................................................................................................14-18

Generating the wrappers.........................................................................................14-21

Building and installing the extension......................................................................14-22

ctypes......................................................................................................................14-23

For more information..............................................................................................14-26

Appendix A: Python Books

Appendix B: Python Gotchas

TOC-6 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 10: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

Intermediate Python 3.x

About this CourseEVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 11: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 About this Course

Welcome!

● We're glad you're here

● You should be a Python programmer at a basic level

● Class has hands-on labs for nearly every chapter

● Please make a name tent

● Instructor name: ____________________________

● Instructor e-mail: ___________________________

Have Fun!

Intermediate Python 3.x ATC-1© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 12: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

About this course rev. 2.0

Classroom etiquette

● Noisemakers off

● No phone conversations

● Come and go quietly during class.

Please turn off boom boxes, cell phone ringers and other noisemakers.

If you need to have a phone conversation, please leave the classroom.

We're adults here; feel free to leave the classroom if you need to use the restroom, make aphone call, etc. You don't have to wait for a lab or break, but please try not to disturb yourfellow students.

If you have an accordion with you, please leave it in the case. Some students may be frightened by it.

ATC-2 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 13: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 About this Course

Course Outline

Day 1Chapter 1 Python Refresher

Chapter 2 OS Services

Chapter 3 Pythonic Programming

Chapter 4 Modules and Packages

Day 2Chapter 5 Classes

Chapter 6 Metaprogramming

Chapter 7 Developer tools

Chapter 8 Database access

Day 3Chapter 9 PyQt4

Chapter 10 Network Programming

Chapter 11 Multiprogramming

Day 4Chapter 12 System Administration and Scripting

Chapter 13 XML and JSON

Chapter 14 Extending Python

Optional: other topics as suggested by you

The actual schedule varies with circumstances. The last day typically includes ad hoc topics requested by students

Intermediate Python 3.x ATC-3© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 14: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

About this course rev. 2.0

Student flesYou will need to load some student fles onto your computer. These fles include

● data for exercises

● example scripts

● answers to exercises

● resources

The fles will be sent to you, or may already be loaded on the computers in the training room.

The fles are in a compressed archive. When you extract them onto your computer, they will all be extracted into a directory named py3interm.

py3interm/EXAMPLES contains the examples from the course manuals.

py3interm/ANSWERS contains sample answers to the labs.

py3interm/DATA contains data fles for examples and labs.

py3interm/SETUP setup scripts and data

The student files do not contain Python itself. It will need to be installed separately. This has probably already been done for you.

ATC-4 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 15: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 About this Course

Extracting the student fles

Unix (includes Unix, Linux, MacOS, etc)

Copy the fle py3interm.tgz to any your home directory, them from there, type:

tar xzvf py3interm.tgzNote: if your version of Unix is elderly, its tar command may not support the z option. If this is so, use this command line instead:

gzip -dc py3interm.tgz | tar xvf -This will create the py3interm directory under your home directory.

Windows

Open the fle py3interm.zip. Extract all fles to desktop or any other convenient location.This will create the folder py3interm.

Included is a file named py3interm_links.html, which contains links to many useful sites related to Python programming

Intermediate Python 3.x ATC-5© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 16: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

About this course rev. 2.0

Examples

● Most examples from course manual provided in EXAMPLES subdirectory

● First line of output shows how script was invoked

For example:

external.py

#!/usr/bin/python

import os

os.system("who")

ls = os.popen("ls -l /tmp","r")

for entry in ls: print(entry[:-1])print()

# backticks equivalenth = os.popen("uname -n").read()[:-1]

print(h)

external.pyjstrick :0 2008-08-25 11:47 jstrick pts/0 2008-08-25 13:06 (:0.0) jstrick pts/1 2008-08-25 13:13 (:0.0) total 44 drwx------ 3 jstrick jstrick 4096 2008-08-25 11:47 gconfd-jstrickdrwx------ 2 root root 4096 2008-08-25 13:10 gconfd-root drwx------ 2 jstrick jstrick 4096 2008-08-25 11:47 keyring-Ii5L9tsrwxr-xr-x 1 jstrick jstrick 0 2008-08-25 11:47 mapping-jstrick drwx------ 2 jstrick jstrick 4096 2008-08-25 18:14 orbit-jstrick drwx------ 2 root root 4096 2008-08-25 13:10 orbit-root srwxr-xr-x 1 jstrick jstrick 0 2008-08-25 11:48 OSL_PIPE_1000_SingleOfficeIPC_709aa55976c37ee189ec71e931.2573 drwx------ 2 jstrick jstrick 4096 2008-08-25 16:28 plugtmp drwx------ 2 jstrick jstrick 4096 2008-08-25 11:47 ssh-uIikNW5481drwxr-xr-x 3 jstrick jstrick 4096 2008-08-25 17:46 svh07.tmp drwx------ 2 jstrick jstrick 4096 2008-08-25 18:14 v1.2170 drwx------ 2 jstrick jstrick 4096 2008-08-25 17:39 v97670 drwx------ 2 jstrick jstrick 4096 2008-08-25 11:47 virtual-jstrick.Hfflbh

gimli

ATC-6 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 17: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 About this Course

Lab Exercises

● Relax – a lab is not a quiz

● Feel free to modify labs

● Ask the instructor for help

● Work on your own scripts or data

● Data is in DATA folder

Intermediate Python 3.x ATC-7© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 18: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

About this course rev. 2.0

Appendices

● Appendix A: Python Books

● Appendix B: Python Gotchas

ATC-8 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 19: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

Intermediate Python 3.x

Chapter 1

Python 3 Refresher

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 20: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 Python 3 Refresher

Variables

● Variables are declared by assignment

● Dynamic typing (AKA "Duck Typing")

Variables are declared by assigning to them. Python does not require explicit type specifers, but sets the type implicitly by examining the value that was assigned. This form of dynamic typing is sometimes called "duck typing", because "if it looks like a duck and quacks like a duck it must be a duck".

Thus, assigning a number to a variable creates a variable of type int, while assigning text to a variable creates a variable of type string. Once a variable is assigned to, it will cause an error if the variable is used with an operator or function that is inappropriate for the type.

A variable cannot be used before it is assigned to.

Examplename = 'Fred Flintstone'count = 0name = 'Fred Flintstone'colors = [ 'red', 'purple', 'green' ]

Typing DisciplinesDynamic Static

Weak awkcsh, ksh, bash

JavaScriptPerlPHP

Visual Basic

Strong PythonCommon Lisp

Ruby

C, C++C#

COBOLFortran

JavaVisual Basic

Intermediate Python 3.x 1-1© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 21: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

Python Refresher rev. 2.0

Basic Python Data types

● Python has many data types

● Use type name builtin to convert

Python has many data types. There are builtin functions to convert from one type to another. If the source type cannot be converted to the target type, a TypeError is thrown.

● Numeric types

• bool

• int

• foat

• complex

● Sequence types

• str

• bytes

• list

• tuple

● Mapping types

• dict

• set

• frozenset

1-2 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 22: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 Python 3 Refresher

Sequences

● Strings are text (arrays of Unicode characters)● s = "text";

● Bytes are arrays of bytes● b = b"text";

● Lists are ordered sets of valuesmy_list = []

● sequence[start:limit:stride]

● Tuples are immutable listsmy_tuple = ()

Python supports four types of sequences – strings, bytes, lists, and tuples. All sequences share a common set of operations, methods, and builtin functions; each type also has operations specifc to that type.

A str object is a list of Unicode characters. A bytes object is a list of bytes.

All sequences support slicing, which means returning a subset of the sequence using the [start,limit,step] syntax.

Examplescolors = [ 'red', 'green', 'blue', 'purple', 'pink', 'yellow', 'black' ]c1 = colors[0] # 'red'c2 = colors[1:4] # 'green', 'blue', 'purple'c3 = colors[-1] # 'black'c4 = colors[:3] # 'red', 'green', 'blue'c5 = colors[3:] # 'purple', 'pink', 'yellow', 'black'

Note that the starting value of a slice is inclusive, while the endingvalue is exclusive.

Intermediate Python 3.x 1-3© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 23: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

Python Refresher rev. 2.0

Mapping Types

● Dictionaries are mapped sets of values

● Sets are similar to dictionaries but contain only keys

● Syntaxd = { }

s = set()

f = frozenset()

Python also supports unordered sets of values. These non-sequential sets of data are also called mapping types.

A dictionary is a set of values indexed by an immutable keyword. Dictionaries are used for many tasks, including mapping one set of values to another, and counting occurrencesof values.

A set is an unindexed set of values. Sets are used to fnd unique values, and to test for membership. There are two types -- the normal set is dynamic (mutable), and a frozenset is fxed (immutable), like a tuple. Use it to specify a fxed set of values.

1-4 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 24: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 Python 3 Refresher

Program structure

● Variables, subroutines, and classes must be declared before use

● Normal order is

- Imports

- Global variables

- Main function

- Subroutines

- Call main function

In Python, modules must be imported before their contents may be accessed. Variables, subroutines, and classes must be declared before they can be used. Thus most scripts are ordered in this way:

1. import statements

2. global variables

3. main function

4. subroutines

5. call main function

You may want to make a template for your Python scripts. Most editors and IDEs support templates or code snippets.

Intermediate Python 3.x 1-5© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 25: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

Python Refresher rev. 2.0

Example

#!/usr/bin/python

#-----------------------------------------------# Imports From Standard Library#-----------------------------------------------import sys

# other imports here...

#-----------------------------------------------# Global variables (capitalized)#-----------------------------------------------

#-----------------------------------------------# Main function#-----------------------------------------------def main(args): pass

#-----------------------------------------------# Function definitions#--------------------------------------------

# other functions here...

#-----------------------------------------------# Program starts here#-----------------------------------------------

if __name__ == '__main__': main(sys.argv)

1-6 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 26: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 Python 3 Refresher

Files and console I/O

● print()

● open()

● input()

Screen output

To output to the screen, use the print() function. print() normally outputs a newline after its arguments, this can be controlled with the end parameter.

print() puts spaces between its arguments by default. To use a different separator, set the sep parameter to the desired separator, which might be an empty string.

Reading fles

To read a fle, open it with the open() function as part of a with statement.

To read it line by line, iterate through the fle with a for loop. To read the entire fle, use fle.read(); to read all the lines into a list, use fle.readlines(). To read a specifed numberof bytes, use fle.read(n).

To navigate within a fle, use fle.seek(offset, whence); to get the current location, use fle.tell().

User input

To get input from the user, use input(). It provides a prompt to the user, and returns a string, with the newline already trimmed.

Intermediate Python 3.x 1-7© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 27: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

Python Refresher rev. 2.0

Conditionals

● Test a Boolean value

● Variations on if

● Syntax

if EXPR:elif EXPR:else:

The conditional statement in Python, like most languages, is if. There are several variations on how if is used. All depend on testing a value to see whether it is true or false.

The following values are false:

False, empty collections, and zero

Everything else is true.

Python has a shortcut if-else that is something like the ?: operator in C, Perl and other curly-brace languages

value1 if condition else value2

Examples

if name == 'root: print("do not run this utility as root")elif name == 'guest': print("sorry – guests are not allowed to run this utility")else: print("starting processing")

limit = sys.args[1] if len(sys.args) > 1 else 100

1-8 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 28: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 Python 3 Refresher

Loops

● Two kinds of loops

● while is used when waiting for a condition (typically waiting for data, as from a fle or database)

● for is used when iterating over a sequence

Python has two kinds of loops.

The while loop is used for reading data, typically from a database or other data source, orwhen waiting for user input to end a loop.

The for loop is used to iterate through a sequence of data. Because Python uses iterators to simplify access to many kinds of data, the for loop is used in places that would use while in most languages. The most frequent example of this is in reading lines from a fle.

while and for loops can also have an else block, which is always executed unless a break statement is executed.

Intermediate Python 3.x 1-9© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 29: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

Python Refresher rev. 2.0

Exampleloops_ex.py

colors = [ 'red', 'green', 'blue', 'purple', 'pink', 'yellow', 'black' ]

for color in colors: print(color) print()

with open('../DATA/mary.txt') as MARY: for line in MARY: print(line,end='') print()

while True: name = input("What is your name? ") if name.lower() == 'q': break print("Welcome,",name)

loops_ex.pyred green blue purple pink yellow black

Mary had a little lamb, Its fleece was white as snow, And everywhere that mary went The lamb was sure to go

What is your name? John Welcome, John What is your name? q

1-10 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 30: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 Python 3 Refresher

Builtins

● 72 builtin functions (v3.2.2)

● Not called from an object or package

● Can work on many different data types

Python has many builtin functions. These provide generic functionality that is not tied to a particular type or package.

They can be applied to many different data types, but not all functions can be applied to all data types.

If you accidentally overwrite a builtin, you can copy it back from the __builtins__ module

Intermediate Python 3.x 1-11© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 31: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

Python Refresher rev. 2.0

Chapter 1 Exercises

Exercise 1-1 (pres_by_state.py)

Using the fle presidents.txt (in the DATA folder), count the number of Presidents who were born in each state. In other words, the output of your script should be a list, sorted by state name, with the state and the number of presidents that were born in that state:

Hint: First declare a dictionary to hold the data. Then read the file in one line at a time. Split each line into fields using a colon as the separator. Add/update the element of the dictionary where the key is the state. Add 1 each time the state occurs.

Arkansas 1 California 1 Connecticut 1 Georgia 1 etc

Exercise 1-2 (pres_dates.py)

Write an interactive script that asks for a president's last name. For each president whose last name matches, print out their date of birth and date of death. For presidents who are still alive, print three asterisks for the date.

For the ambitious --1. Make the name search case-insensitive2. Change your script to print out matches for partial names – so "jeff" would fnd "Jefferson", e.g.

1-12 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 32: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 PyQt4

Chapter 9 Objectives

● See the big picture of PyQT programming

● Understand event-driven programming

● Code a minimal PyQT application

● Use the QT designer to GUIs

● Wire up the generated GUI to event handlers

● Add standard components to a GUI application

● Use predefned dialogs

● Design and use custom dialogs

Intermediate Python 3.x 9-1© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 33: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

PyQt4 rev. 2.0

What is PyQt4?

● Python Bindings for Qt4 library

● Qt4 is written in C++ but ported to many languages

● Complete GUI library

● Cross-platform (OS X, Windows, Linux, etc.)

● Hides platform-specifc details

PyQt4 is a package for Python that provides binding to the generic Qt4 graphics programming library. Qt4 provides a complete graphics programming framework, and looks "native" across various platforms. In addition to graphics components, it includes database access and many other tools.

It hides the platform-specifc details, so PyQt programs are portable.

Blackberry has created a framework named Cascades that is built on top of PyQt4, and which you can use to create Blackberryapps.

Cascades provides its own layout widgets (AbsoluteLayout, StackLayout, DockLayout) to use instead of the standard VBoxLayout, HBoxLayout, etc. Programming with Cascades is very similar to normal PyQt4 development.

For more information, see

http://developer.blackberry.com/cascades/

9-2 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 34: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 PyQt4

Event Driven Applications

● Application starts event loop

● When event occurs, goes to handler function, then back to loop

● Terminate event ends the loop (and the app)

GUI programs are different from conventional, procedural applications. Instead of the programmer controlling the order of execution via logic, the user controls the order of execution by manipulating the GUI.

To accomplish this, starting a GUI app launches an event loop, which "listens" for user-generated events, such as key presses, mouse clicks, or mouse motion. If there is a method associated with the event (AKA "event handler") (AKA "slot" in PyQt4), the method is invoked.

Intermediate Python 3.x 9-3© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 35: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

PyQt4 rev. 2.0

GUI Application Flow Chart

9-4 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 36: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 PyQt4

External Anatomy of a PyQt4 Application

The main window widget has several predefned areas.

The menu bar area contains the usual File, Edit, and other standard menus.

The tool bar areas can contain any tool bar buttons.

The dock windows area contains any docked windows, which can be docked in any of thedoc areas, or which can foat freely. They have their own title bar with close, minimize and maximize buttons.

The status bar can contain any other widgets, typically labels, but anything is fair game.

None of the above are required, and if not present will not take up any screen space.

The central widget is the main widget of the application. It is usually a QWidget object containing a layout object such as VBoxLayout, HBoxLayour, or GridLayout.

Intermediate Python 3.x 9-5© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 37: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

PyQt4 rev. 2.0

Internal Anatomy of a PyQt4 Application

● Extend (subclass) QmainWindow

● Call show() on main class

The normal (and convenient) approach is to subclass QMainWindow to create a specialized class for your application. Within this class, self is the main window of the application. You can attach widgets to and call setup methods from self.

QApplication is an object which acts as the application itself. You need to create a QApplication object and pass the command line arguments to it. To start your programincall the exec_() method on your application object, after calling show() on the main window to make it visible.

Exampleqt_hello.py

import sysfrom PyQt4.QtGui import *

class HelloWindow(QMainWindow):

def __init__(self, parent = None): QMainWindow.__init__(self, parent) self._label = QLabel("Hello PyQt4 World") self.setCentralWidget(self._label)

if __name__ == "__main__": app = QApplication(sys.argv) main_window = HelloWindow() main_window.show() app.exec_()

9-6 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 38: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 PyQt4

Using designer

● GUI for building GUIs

● Builds applications, dialogs, and widgets

● Outputs generic XML that describes GUI

● pyuic4 generates Python from XML

● Import generated code in main module

The designer tool makes it fast and easy to generate any kind of GUI.

To get started with the designer, choose New... from the File menu.

Select Main Window. (You can also use designer to create dialogs and widgets). This will create a blank application window. It will already have a menu bar and a status bar. Itis ready for you to drag layouts and widgets as needed.

Be sure to change the objectName property of the QMainWindow object in the Property Editor. This (with "Ui_" prefxed) will be the name of the GUI class generated by pyuic4.

To set the title of your application, which will show up on the title bar, select the QmainWindow object in the Object Inspector, then open the QWidget group of propertiesin the Property Editor. Enter the title in the windowTitle property.

Be sure to give your widgets meaningful names, so when you have to use them in your main program, you know which widget is which. A good approach is a short prefx that describes the kind of widget (such as "bt" for QpushButton or "cb" for QcomboBox) followed by a descriptive name. Good examples are 'btOpenFile', 'cbSelectState', and 'labHello'. There are no standard prefxes, so use whatever makes sense to you.

You can just drag widgets onto the main window and position them, but in general you will use layouts to contain widgets, as described later.

For each of the example programs, the source is provide in the EXAMPLES folder, including the designer fle (which has the extension .ui). For a gi

Intermediate Python 3.x 9-7© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 39: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

PyQt4 rev. 2.0

The designer tool

9-8 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 40: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 PyQt4

Anatomy of a designer-based application

● Name MainWindow Hello2 (for example)

● Save from designer as hello2.ui

● Use pyuic4 to generate ui_hello2 .py from Foo.ui

● Subclass QMainWindow

● Add instance of Ui_ Hello2 to main window

● Call setupUi from Ui_ Hello2

● Instantiate main window and call show()

● Start application

Use designer to create GUI - set name of MainWindow as "Hello2" - save as hello2.uiUse pyuic4 to generate Python code:

pyuic4 hello2.ui > ui_hello2.py

qt_hello2.py

import sys

from PyQt4.QtGui import QMainWindow, QApplication from ui_hello2 import Ui_Hello2 # import generated interface

class Hello2Main(QMainWindow): def __init__(self): QMainWindow.__init__(self)

# add an instance of the generated GUI to the main window class self.ui = Ui_Hello2() # assign instance to variable self.ui.setupUi(self) # set up generated interface

if __name__ == "__main__": app = QApplication(sys.argv) main = Hello2Main() main.show() sys.exit(app.exec_())

You can use the above as a template for any designer-generated application. Just change Hello2 to the name you gave your GUI in the designer, observingdifferences in case.

In Komodo Edit, you can easily automate such a template

Intermediate Python 3.x 9-9© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 41: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

PyQt4 rev. 2.0

Naming conventions

● Keep names consistent across applications

● Use "application name" throughout

● Pay attention to case

Using consistent names for the main window object can pay off in several ways. First, you'll be less confused. Second, you can write scripts or IDE macros to generate Python code from the designer output. Third, you can create standard templates which contain the boilerplate PyQt4 code to set up and run the GUI.

If application name is Xyz:

1. For the QMainWindow object

1. set objectName to Xyz

2. set windowTitle to Xyz

2. Save designer fle as xyz.ui

3. Redirect output of pyuic4 on xyz.ui to ui_xyz.py

4. In main program, use this import

from ui_xyz import Ui_Xyz

Of course, names are arbitrary. You can name any of these anything you like, but consistency can really help simplify your life.

9-10 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 42: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 PyQt4

Common Widgets

● QLabel, QPushButton, QLineEdit, QComboBox

● There are many more

Qt describes many widgets; some are simple, and some are complex. Some of the most basic are Qlabel, QPushButton, QLineEdit, and QComboBox.

QLabel is a widget with some text. QPushButton is just a clickable button. QLineEdit is aone-line entry blank. QComboBox shows a list of values, and allows a new value to be entered.

QLineEdit widgets are typically paired with QLabels. Using the property editor in designer, set buddy property to be the matching QLineEdit. This allows the accelerator (specifed with &letter in the label text) of the label to place focus on the paired widget.

Intermediate Python 3.x 9-11© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 43: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

PyQt4 rev. 2.0

Exampleqt_common_widgets.py

import sys

from PyQt4.QtGui import QMainWindow, QApplication from ui_commonwidgets import Ui_CommonWidgets

class CommonWidgetsMain(QMainWindow): def __init__(self): QMainWindow.__init__(self)

self.ui = Ui_CommonWidgets() self.ui.setupUi(self)

# populate the combo box for k,v in (('apple',1),('banana',2),('mango',3)): self.ui.cbFruits.insertItem(v,k,v)

if __name__ == "__main__": app = QApplication(sys.argv) main = CommonWidgetsMain() main.show() sys.exit(app.exec_())

9-12 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 44: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 PyQt4

Layouts

● QVBoxLayout (vertical, like pancakes)

● QHBoxLayout (horizontal, like books on a shelf)

Most applications need more than one widget in the central widget area. To create a layout using multiple widgets, create a Qwidget object and set its layout to either a QVBoxLayout or a QHBoxLayout. You can add widgets or nested layouts to these layouts, to create the arrangement you need.

These layouts can be resized; widgets attached to them will grow and shrink as needed (by default – all PyQt4 behavior can be changed in the Property editor, or programmatically).

It is usually easiest to work from the inside out. In the example below, a QHBoxLayout was created frst, then 3 labels added to it. Then a QVBoxLayout was created, and after adding two labels to it, the QHBoxLayout was dragged into the QVBoxLayout, then the fourth label.

Exampleqt_layouts.py

import sys

from PyQt4.QtGui import QMainWindow, QApplication from ui_layouts import Ui_Layouts

class LayoutsMain(QMainWindow): def __init__(self): QMainWindow.__init__(self)

self.ui = Ui_Layouts() self.ui.setupUi(self)

if __name__ == "__main__": app = QApplication(sys.argv) main = LayoutsMain() main.show() sys.exit(app.exec_())

Intermediate Python 3.x 9-13© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 45: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

PyQt4 rev. 2.0

Selectable Buttons

● QRadioButton, QCheckBox

● Can be grouped

There are two kinds of selectable buttons. QRadioButtons are used in a group, where only one of the group can be checked. QCheckBoxes are individual, and can be checked or unchecked.

By default, Radiobuttons are autoExclusive – all radio buttons that have the same parent are grouped. If you need more than one group of radio buttons to share a parent, use QButtonGroup to group them.

Use the isChecked() method to determine whether a button has been selected. Use the checked property to mark a button as checked.

Exampleqt_selectable.py

import sys

from PyQt4.QtGui import QMainWindow, QApplication from ui_selectables import Ui_Selectables

class SelectablesMain(QMainWindow): def __init__(self): QMainWindow.__init__(self)

self.ui = Ui_Selectables() self.ui.setupUi(self)

if __name__ == "__main__": app = QApplication(sys.argv) main = SelectablesMain() main.show() sys.exit(app.exec_())

9-14 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 46: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 PyQt4

Actions and Events

● Widgets have predefned actions that can be handled

● Handler is ordinary method

● Use widget.action.connect(method)

● Pass in function object; don't call function

● Action is clicked, triggered, etc.

● Event names are predefned; override in main class

To add an action to a widget, use the connect() method of the appropriate action, which isan attribute of the widget. For instance, if you have a QPushButton object pb, you can set the action with pb.clicked.connect(method).

Actions end with -ed, suchs as clicked, connected, triggered, etc.

Other events can be handled by using reimplementing methods, such as keyPressEvent. Event handlers are passed the event object, which has more detail about the event, such as the key pressed, the mouse position, or the number of mouse clicks.

To get the widget that generated the event (AKA the sender), use self.sender() in the handler function.

If the action needs parameters, the simplest thing to do is use oneor more attributes (instance variables) of the main class. Otherwise, you'd need to use a closure (nested function) or other more complex approach.

Intermediate Python 3.x 9-15© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 47: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

PyQt4 rev. 2.0

Exampleqt_events.py

import sys import types

from PyQt4.QtGui import QMainWindow, QApplication from ui_events import Ui_Events

def fprint(*args): """ print and flush the output buffer so text shows up immediately """ for arg in args: print(arg, end='') print() sys.stdout.flush()

class EventsMain(QMainWindow): FRUITS = dict(A='Apple', B='Banana', C='Cherry', D='Date')

def __init__(self): QMainWindow.__init__(self)

self.ui = Ui_Events() self.ui.setupUi(self)

# set the File->Quit handler self.ui.actionQuit.triggered.connect(lambda:self.close())

# set the Edit->Clear Name Field handler self.ui.actionClear_name_field.triggered.connect(self._clear_field)

# use the same handler for all 4 buttons self.ui.pb_A.clicked.connect(self._pushed) self.ui.pb_B.clicked.connect(self._pushed) self.ui.pb_C.clicked.connect(self._pushed) self.ui.pb_D.clicked.connect(self._pushed)

self.setup_mouse_move_event_handler()

self.ui.checkBox.toggled.connect(self._toggled) self.ui.checkBox.clicked.connect(self._clicked) def setup_mouse_move_event_handler(self): def mme(self, mouse_ev): self.ui.statusbar.showMessage("Motion: {0},{1}".format( mouse_ev.x(), mouse_ev.y(), 0) # 2nd param is timeout ) # add method instance to label dynamically self.ui.label.mouseMoveEvent = types.MethodType(mme, self)

def keyPressEvent(self, key_ev): """ Generated on keypresses (except in text widgets) """ key_code = key_ev.key() char = chr(key_code) if key_code < 128 else 'Special' fprint("Key press: {0} ({1})".format(key_code, char))

9-16 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 48: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 PyQt4 def mousePressEvent(self, mouse_ev): """ generated when mouse button is pressed """ fprint("Press:", mouse_ev.x(), mouse_ev.y())

def mouseReleaseEvent(self, mouse_ev): fprint("Release:", mouse_ev.x(), mouse_ev.y())

def _toggled(self, mouse_ev): fprint("Toggle")

def _clicked(self, mouse_ev): fprint("Click")

def _checked(self, mouse_ev): fprint("Toggle")

def _pushed(self): sender = self.sender() button_text = str(sender.text()) if button_text in EventsMain.FRUITS: sender.setText(EventsMain.FRUITS[button_text])

def _clear_field(self): self.ui.leName.setText('')

if __name__ == '__main__': app = QApplication(sys.argv) main = EventsMain() main.show() sys.exit(app.exec_())

Intermediate Python 3.x 9-17© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 49: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

PyQt4 rev. 2.0

Menu Bar

● Add menus and submenus to menu bar

● Add actions to submenus

You can just start typing on the menus in the menu bar to add menu items, separators, andsubmenus. To make the menus do something, see the examples in the previous topics. Note this section of code:

self.ui.actionQuit.triggered.connect(lambda:self.close()) self.ui.actionClear_name_field.triggered.connect(self._clear_field)

This is how to attach a callback function to a menu item. By default, the designer will name menu choices based on the text in the menu. You can name the menu items anything, however.

9-18 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 50: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 PyQt4

Status Bar

● Displays at bottom of main window

A status bar is a row at the bottom of the main window which can be used for text messages. A default status bar is automatically part of a GUI based on QmainWindow. It is named "statusbar".

To put a message on the status bar, use the showMessage() method of the status bar object. The frst parameter is a string containing the message; the second parameter is the timeout in milliseconds. A timeout of 0 means display until overwritten. To clear the message, use either removeMessage(), or display an empty string.

Intermediate Python 3.x 9-19© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 51: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

PyQt4 rev. 2.0

Exampleqt_statusbar.py

import sys from PyQt4.QtGui import QMainWindow, QApplication from ui_statusbar import Ui_StatusBar

class StatusBarMain(QMainWindow): def __init__(self): QMainWindow.__init__(self)

self._count = 0 # Setup the user interface from Designer. self.ui = Ui_StatusBar() self.ui.setupUi(self)

self.ui.btPushMe.clicked.connect(self._pushed) self._update_statusbar() def _pushed(self, ev): self._update_statusbar() def _update_statusbar(self): self._count += 1 msg = "Count is " + str(self._count) self.ui.statusbar.showMessage(msg, 0) if __name__ == '__main__': app = QApplication(sys.argv) main = StatusBarMain() main.show() sys.exit(app.exec_())

9-20 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 52: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 PyQt4

Using Predefned Dialogs

● Predefned dialogs for common tasks

● Files, Messages, Colors, Fonts, Printing

● Use static methods for convenience.

PyQt defnes several standard popup dialogs for common GUI tasks. The chart below lists them. Most of the standard dialogs can be invoked directly; however, most also provide some convenient static methods that provide more fne-grained control. These static methods return an appropriate value, typically a user selection.

Standard Dialogs (with Convenience Methods)Dialog Description

QColorDialog.getColor Select a color

QErrorMessage.showMessage Display an error messages

QFileDialog.getExistingDirectory

QFileDialog.getOpenFileName

QFileDialog.getOpenFileNameAndFilter

QFileDialog.getOpenFileNames

QFileDialog.getSaveFileName

QFileDialog.getSaveFileNameAndFilter

Select fles or folders

QFontDialog Select a font

QInputDialog.getText

QInputDialog.getInteger

QInputDialog.getDouble

QInputDialog.getItem

Get input from user

QMessageBox Display a modal message

QPageSetupDialog Select page-related options for printer

QPrintPreviewDialog Display print preview

QProgressDialog Display a progress windows

QWizard Guide user through step-by-step process

Intermediate Python 3.x 9-21© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 53: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

PyQt4 rev. 2.0

Exampleqt_std_dialogs.pyimport sys import os

from PyQt4.QtGui import QMainWindow, QApplication, QColor from PyQt4.QtGui import QFileDialog, QColorDialog, QErrorMessage, QInputDialog from ui_standarddialogs import Ui_StandardDialogs

class StandardDialogsMain(QMainWindow): def __init__(self): QMainWindow.__init__(self)

self.ui = Ui_StandardDialogs() self.ui.setupUi(self)

self.ui.actionQuit.triggered.connect(lambda:self.close())

# Connect up the buttons. self.ui.btFile.clicked.connect(self._choose_file) self.ui.btColor.clicked.connect(self._choose_color) self.ui.btMessage.clicked.connect(self._show_error) self.ui.btInput.clicked.connect(self._get_input) # self.ui.BUTTON_NAME.clicked.connect(self._pushed)

def _choose_file(self): full_path = QFileDialog.getOpenFileName(self, 'Open file', os.getcwd()) file_name = os.path.basename(str(full_path)) self.ui.statusbar.showMessage("You chose: " + file_name)

def _choose_color(self): color = QColor() result = QColorDialog.getColor(color) self.ui.statusbar.showMessage( "You chose #{0:02x}{1:02x}{2:02x} ({0},{1},{2})".format( result.red(), result.green(), result.blue() ) )

def _show_error(self): em = QErrorMessage(self) em.showMessage("There is a problem") self.ui.statusbar.showMessage('Diplaying Error')

def _get_input(self): text, ok = QInputDialog.getText(self, 'Input Dialog', 'Enter your name:') if ok: self.ui.statusbar.showMessage("Your name is " + text) if __name__ == '__main__': app = QApplication(sys.argv) main = StandardDialogsMain() main.show() sys.exit(app.exec_())

9-22 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 54: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 PyQt4

Creating Custom Dialogs

● Choose Dialog option when starting a new GUI

● Dialog can be standalone or called from other GUI

To create a custom dialog box, start with one of the Dialog options, , rather than QMainWindow. The dialog will start out with a QButtonBox containing standard buttons.You can add more buttons to the QButtonBox if needed.

Add widgets to the dialog as needed. The dialog can be standalone if your application only needs the dialog, and you don't need menus or a status bar.

You can, of course, call the dialog from some other GUI, typically a main window, but not necessarily.

The dialog can't be called directly. The designer doesn't really create a ready-to-use dialog, rather it creates a GUI that can be used in a dialog. You have to create a generic dialog object and setup the dialog GUI, similarly to what happens in the main window.

The general idea is:

from ui_yourdialog import Ui_YourDialog...dlg = QDialog() ui = Ui_YourDialog() ui.setupUi(dlg) if dlg.exec_(): # use pressed OK pass # do something with data from dialogelse: pass # typically do nothing

Intermediate Python 3.x 9-23© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 55: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

PyQt4 rev. 2.0

Exampleqt_developerinfo.pyimport sys

from PyQt4.QtGui import QMainWindow, QApplication, QDialog from ui_developerinfo import Ui_DeveloperInfo from ui_developerinfodialog import Ui_DeveloperInfoDialog

class DeveloperInfoMain(QMainWindow): def __init__(self): QMainWindow.__init__(self)

self.ui = Ui_DeveloperInfo() self.ui.setupUi(self)

self.ui.actionQuit.triggered.connect(lambda:self.close())

self.ui.btGetInfo.clicked.connect(self._get_info)

def _get_info(self): dlg = QDialog() ui = Ui_DeveloperInfoDialog() ui.setupUi(dlg) if dlg.exec_(): name = ui.leName.text() email = ui.leEmail.text() if ui.rbPython.isChecked(): lang = 'Python' elif ui.rbPerl.isChecked(): lang = 'Perl' elif ui.rbRuby.isChecked(): lang = 'Ruby' self.ui.labInfo.setText("{0}\n{1}\n{2}".format(name, email, lang))

if __name__ == '__main__': app = QApplication(sys.argv) main = DeveloperInfoMain() main.show() sys.exit(app.exec_())

9-24 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 56: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 PyQt4

Tabs

● Use a Tab Widget

● In designer under "Containers"

● Each tab can have a name

A Tab Widget contains one or more tabs, each of which can contain a widget, either a single widget or some kind of container.

As usual, tabs can be created in the designer. You should give each tab a unique name, sothat in your main code you can access them programmatically.

Drag a Tab Widget to your application and place it. Then you casn add more tabs by right-clicking on a tab and selecting Insert Page. You can then go to the properties of the tab widget and set the properties for the currently select tab. Select other tabs and change their properties as appropriate.

Whichever tab is selected when you generate the UI fle will be selected when you start your application.

Intermediate Python 3.x 9-25© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 57: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

PyQt4 rev. 2.0

Exampleqt_tabs.py

import sys

from PyQt4.QtGui import QMainWindow, QApplication from ui_tabs import Ui_Tabs

class TabsMain(QMainWindow): def __init__(self): QMainWindow.__init__(self)

self.ui = Ui_Tabs() self.ui.setupUi(self)

self.ui.actionQuit.triggered.connect(lambda:self.close()) self.ui.actionA.triggered.connect(lambda: self._show_tab('A')) self.ui.actionB.triggered.connect(lambda: self._show_tab('B')) self.ui.actionC.triggered.connect(lambda: self._show_tab('C')) def _show_tab(self, which_tab): if which_tab == 'A': self.ui.tabWidget.setCurrentIndex(0) self.ui.labA.setText('Aardvark') elif which_tab == 'B': self.ui.tabWidget.setCurrentIndex(1) self.ui.labB.setText('Bonobo') elif which_tab == 'C': self.ui.tabWidget.setCurrentIndex(2) self.ui.labC.setText('Coatimundi')

if __name__ == '__main__': app = QApplication(sys.argv) main = TabsMain() main.show() sys.exit(app.exec_())

9-26 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 58: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 PyQt4

Niceties

● Styling Text

● Tooltips

Fonts can be confgured via the designer. Choose any widget in the Object inspector, then search for the font property group in the Property Editor. You can change the font family, the point size, and weight and slant of the text.

You can further style a widget by specifying a string containing a vaid CSS (cascading style sheet). In the CSS, the selectors are the object names. Either of the following approaches can be used:

widget.setStyleSheet('QPushButton {color: blue}')widget.setStyleSheet(open(cssfile).read())Tooltips can be added via the designer. Search for the toolTip property and type in the desired text.

Intermediate Python 3.x 9-27© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 59: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

PyQt4 rev. 2.0

Working with Images

● Display images via QLabels

● Create a QPixmap of the image

● Assign pixmap to label

To display an image, create a QPixmap object from the graphics fle. Then assign the pixmap to a QLabel. The image may be scaled or resized.

The images in the example program are scaled to ft the original label. This is why they are distorted.

9-28 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 60: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 PyQt4Exampleqt_images.py

import sys

from PyQt4.QtGui import QMainWindow, QApplication, QPixmap from ui_images import Ui_Images

class ImagesMain(QMainWindow): def __init__(self): QMainWindow.__init__(self)

# Set up the user interface from Designer. self.ui = Ui_Images() self.ui.setupUi(self)

self.ui.actionQuit.triggered.connect(lambda:self.close())

self.ui.actionPictureA.triggered.connect( lambda: self._show_picture('A') ) self.ui.actionPictureB.triggered.connect( lambda: self._show_picture('B') ) self.ui.actionPictureC.triggered.connect( lambda: self._show_picture('C') )

def _show_picture(self, which_picture): if which_picture == 'A': image_file = 'apple.png' label = self.ui.labA elif which_picture == 'B': image_file = 'banana.jpg' label = self.ui.labB elif which_picture == 'C': image_file = 'cherry.jpg' label = self.ui.labC img = QPixmap('../DATA/' + image_file) label.setPixmap(img) label.setScaledContents(True)

if __name__ == '__main__': app = QApplication(sys.argv) main = ImagesMain() main.show() sys.exit(app.exec_())

Intermediate Python 3.x 9-29© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 61: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

PyQt4 rev. 2.0

Complete ExampleThis is an application that lets the user load a fle of words, then shows all words that match a specifed regular expression

import sys import re

from PyQt4.QtGui import QMainWindow, QApplication, QFileDialog from ui_wordfinder import Ui_WordFinder

class WordFinderMain(QMainWindow): def __init__(self): QMainWindow.__init__(self)

# Set up the user interface from Designer. self.ui = Ui_WordFinder() self.ui.setupUi(self)

self.ui.actionQuit.triggered.connect(lambda:self.close())

self.ui.actionLoad.triggered.connect(self._load_file)

self.ui.lePattern.returnPressed.connect(self._search) self.ui.btSearch.clicked.connect(self._search) def _load_file(self): file_name = QFileDialog.getOpenFileName( self, 'Open file for matching', '/' ) if file_name: with open(file_name) as F: self._words = [ line.rstrip() for line in F ]

self._numwords = len(self._words) self.ui.teText.clear() self.ui.teText.insertPlainText( '\n'.join(self._words))

9-30 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 62: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

rev. 2.0 PyQt4def _search(self): pattern = str(self.ui.lePattern.text()) if pattern == '': pattern = '.' rx = re.compile(pattern) self.ui.teText.clear() self.ui.lePattern.setEnabled(False) # self.lePattern.setVisible(False) count = 0 for word in self._words: if rx.search(word): self.ui.teText.insertPlainText(word + '\n') count += 1 self.ui.lePattern.setEnabled(True) #self.ui.lePattern.setVisible(True) self.ui.statusbar.showMessage( "Matched {0} out of {1} words".format(count,self._numwords), 0 )

if __name__ == '__main__': app = QApplication(sys.argv) main = WordFinderMain() main.show() sys.exit(app.exec_())

Intermediate Python 3.x 9-31© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited

Page 63: COPY INTERMEDIATE PYTHON 3 - ITCourseware€¦ · Using predefned dialogs.....9-21 Creating custom dialogs ... Welcome! We're glad you're ... You don't have to wait for a lab or break,

PyQt4 rev. 2.0

Chapter 9 Labs

Exercise 9-1 (gpresinfo_qt.py)

Using the Qt designer, write a GUI application to display data from the presidentsqlite or presidentmysql module. It should have at least the following components:

● A text feld (use Entry) for entering the term number

● A Search button for retrieving data

● An Exit button

● A widget or widgets to display the president's information – you could use a Text widget, multiple Labels, or whatever suits your fancy.

Be creative. Use color and layout to make your application fun.

For the ambitious, provide a combo box of all available presidents rather than making the user type in the name manually.

For the even more ambitious, implement a search function – let a user type text in a blank, and return a list of presidents which matches the text. E.g., "jeff" would retrieve "Jefferson, Thomas", and "John" would retrieve "Adams, John", as well as"Kennedy, John", "Johnson, Lyndon" and so forth

9-32 Intermediate Python 3.x© 2015 CJ Associates

EVALUATION COPY

Unauthorized Reproduction or Distribution Prohibited